标签:router for clist lock text back color r.js view
最近自学了一下NodeJS,然后做了一个小demo,实现歌曲的添加、修改、播放和删除的功能,其中自然要实现音乐和图片的上传功能。于是上网查找资料,找到了一个formidable插件,该插件可以很好的实现文件的上传功能。该小demo用到了MySQL数据库,所有的数据都存放到了数据库中。下面简单说一些如何使用。
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.‘); })
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"
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文件中的依赖不用多说。
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(‘/‘); }) }) };
标签:router for clist lock text back color r.js view
原文地址:http://www.cnblogs.com/liboxncg/p/6001297.html