Home  >  Article  >  Web Front-end  >  NodeJS uses formidable to implement file upload

NodeJS uses formidable to implement file upload

高洛峰
高洛峰Original
2016-12-08 16:16:421243browse

I recently learned NodeJS by myself, and then made a small demo to implement the functions of adding, modifying, playing and deleting songs. Of course, the function of uploading music and pictures must be implemented. So I searched for information online and found a formidable plug-in, which can implement the file upload function very well. This small demo uses the MySQL database, and all data is stored in the database. Here's a brief explanation of how to use it.

1. Create the main app.js file

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 form in the
add.html file:

<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>

Note: method="post" enctype= "multipart/form-data"

3. Create the router.js file

const express = require(&#39;express&#39;);
const router = express.Router();
const handler = require(&#39;./handler&#39;);
  
router
  .get(&#39;/&#39;, handler.showIndex)
  .get(&#39;/musicList&#39;, handler.getMusicList)
  .get(&#39;/add&#39;, handler.showAdd)
  .post(&#39;/add&#39;, handler.doAdd)
  .get(&#39;/edit&#39;, handler.showEdit)
  .post(&#39;/edit&#39;, handler.doEdit)
  .get(&#39;/remove&#39;, handler.doRemove)
  
module.exports = router;

Note: It goes without saying that the dependencies in the router.js file go without saying.

4. Create handler.js file

const formidable = require(&#39;formidable&#39;);
const config = require(&#39;./config&#39;);
const db = require(&#39;./common/db&#39;);
const path = require(&#39;path&#39;);
const fs = require(&#39;fs&#39;);
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(&#39;INSERT INTO music (title,singer,music,img) VALUES (?,?,?,?)&#39;, [
      title,
      singer,
      music,
      img
    ], (err, rows) => {
      if (err) {
        throw err;
      }
      res.redirect(&#39;/&#39;);
    })
  })
};


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn