在Node.js中获取表单数据

时间:2018-09-05 18:43:35

标签: node.js express form-data body-parser

我在nodejs上有一个应用程序,并且已经收到json格式的请求(这里没有问题)。

当我想通过表单数据上传视频时出现问题。这是我的一些代码:

Server.js

var express = require('express');
var bodyparser = require('body-parser');

var app = express();

app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
require('./routes/routes')(app);

Routes.js

module.exports = function(app){
app.post('/save', ensureAuthenticated, activity.publish); //JSON REQUEST
app.post('/video', ensureAuthenticated, activity.video); //FORM-DATA REQUEST
}

我尝试使用express-formidable(在Server.js中),但是它破坏了我的“ / save”路由。有人有主意吗?

1 个答案:

答案 0 :(得分:4)

我建议您使用multer

https://github.com/expressjs/multer

示例:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})