HTML + Node.jsfile upload

请帮我解决这个问题。 结果我得到空值

HTML代码

<form method="post" enctype="multipart/form-data" action="/file-upload"> <input type="text" name="username"> <input type="password" name="password"> <input type="file" name="thumbnail"> <input type="submit"> </form> 

Node.js的

 var express = require('express'); var http = require('http'); var request = require('request'); var bodyParser = require('body-parser'); var app = express(); app.use(express.static(__dirname + '/app/')); // parse urlencoded request bodies into req.body app.use(bodyParser.urlencoded({ extended: true })); var server = app.listen(8080,function(){ console.log("Node.js image upload"); }); app.post('/file-upload', function(req, res, next) { console.log(req.body); console.log(req.files); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Success\n'); }); 

       

网上收集的解决方案 "HTML + Node.jsfile upload"

body-parser不能处理multipart / form-data

你应该使用像穆勒或公务员

处理multipart / form-data需要一些复杂的逻辑,每一个处理它的包都有很多的设置

由于enctype="multipart/form-data"enctype="multipart/form-data" ,你遇到了问题。 您将需要安装Muller包来处理这些。

基本用法是这样的:

 //Include the package var multer = require('multer'); var uploadTmp = multer({ dest: 'uploads/' }); // Use a middleware to handle files app.post('/file-upload',uploadTmp.single('thumbnail'), function(req, res, next) { 

您可以使用npm模块formidable的服务窗体多部分数据。 以下是一个例子:

  app.post('/file-upload', function(req, res, next) { var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files) { console.log('form parse'); }); form.on('field',function(name,value){ console.log('in field',name,value);//gives you the field names with value }); form.on('file',function(name,value){ console.log('in file'); }); form.on('end', function(fields, files) { this.openedFiles[x].path; //gives the file path }); });