我在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”路由。有人有主意吗?

最佳答案

我建议你用穆勒

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

关于node.js - 在Node.js中获取表单数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52191614/

10-09 17:54