时间:2021-07-01 10:21:17 帮助过:13人阅读
1.创建app.js主文件
const express = require('express'); const router = require('./router'); const path = require('path'); const bodyParser = require('body-parser'); const app = express(); //静态资源服务 app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); app.use('/node_modules', express.static(path.join(__dirname, 'node_modules'))); //配置模板引擎 app.set('views', path.join(__dirname, 'views')); app.engine('.html', require('ejs').renderFile); app.set('view engine', 'html'); //配置解析普通表单post请求体 app.use(bodyParser.urlencoded({extended:false})); //加载路由系统 app.use(router); app.listen(3000, '127.0.0.1', () => { console.log('server is running at port 3000.'); })
2.html文件中的form表单
add.html文件:
<form action="/add" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="title">标题</label> <input type="text" class="form-control" id="title" name="title" placeholder="请输入音乐标题"> </div> <div class="form-group"> <label for="artist">歌手</label> <input type="text" class="form-control" id="singer" name="singer" placeholder="请输入歌手名称"> </div> <div class="form-group"> <label for="music_file">音乐</label> <input type="file" id="music" name="music" accept="audio/*"> <p class="help-block">请选择要上传的音乐文件.</p> </div> <div class="form-group"> <label for="image_file">海报</label> <input type="file" id="poster" name="img" accept="image/*"> <p class="help-block">请选择要上传的音乐海报.</p> </div> <button type="submit" class="btn btn-success">点击添加</button> </form>
注意:method="post" enctype="multipart/form-data"
3.创建路由router.js文件
const express = require('express'); const router = express.Router(); const handler = require('./handler'); router .get('/', handler.showIndex) .get('/musicList', handler.getMusicList) .get('/add', handler.showAdd) .post('/add', handler.doAdd) .get('/edit', handler.showEdit) .post('/edit', handler.doEdit) .get('/remove', handler.doRemove) module.exports = router;
注意:router.js文件中的依赖不用多说。
4.创建handler.js文件
const formidable = require('formidable'); const config = require('./config'); const db = require('./common/db'); const path = require('path'); const fs = require('fs'); exports.doAdd = (req, res) => { const form = new formidable.IncomingForm(); form.uploadDir = config.uploadDir;//上传文件的保存路径 form.keepExtensions = true;//保存扩展名 form.maxFieldsSize = 20 * 1024 * 1024;//上传文件的最大大小 form.parse(req, (err, fields, files) => { if (err) { throw err; } const title = fields.title; const singer = fields.singer; const music = path.basename(files.music.path); const img = path.basename(files.img.path); db.query('INSERT INTO music (title,singer,music,img) VALUES (?,?,?,?)', [ title, singer, music, img ], (err, rows) => { if (err) { throw err; } res.redirect('/'); }) }) };