使用node.js上传文件时出错
使用下面的代码,当我尝试上传文件时,浏览器只是一直加载。 任何想法为什么?
app.js
var formidable = require('formidable'), http = require('http'), util = require('util'); app.get('/song/add', function (req, res) { res.writeHead(200, {'content-type': 'text/html'}); res.end( '<form action="/song/upload" enctype="multipart/form-data" method="post">'+ '<input type="text" name="title"><br>'+ '<input type="file" name="upload" multiple="multiple"><br>'+ '<input type="submit" value="Upload">'+ '</form>' ); }); app.post('/song/upload', function (req, res) { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields, files: files})); }); return; });
只需在代码中删除该行( app.use(express.bodyParser())
),我相信这应该工作。
但是你为什么要使用强大的? 我相信express body parser是基于强大的,而且使用起来更清洁。 既然它甚至parsing了其他types的body,除了JSON之类的表单types外,如果bodytypes不被支持,强大的将会抛出一个错误。 如果你的代码中有app.use(express.bodyParser())
,那么你可以这样做来得到你想要的:
app.post('/song/upload', function(req, res){ res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end(util.inspect(req.body)); return; });
您可能已经打开了快速文本parsing器选项。 检查您的configuration的东西,如:
app.use(express.bodyParser())
我认为问题在于,Formidable正在期待这个文件的stream事件,当您的app.post
callback被调用时,它们已经被Express使用。 由于form.parse
callback仅在end
触发,因此不会呈现任何响应。
解决方法是使用Express或Formidable,如果你想使用Formidable你可以禁用configuration选项。
我在这里看到的问题是新的身体分析器(自连接1.8.0)。 如果你想使用强大的新的连接,你需要从正文parsing器中删除多部分分析器:
delete express.bodyParser.parse['multipart/form-data'];
不要在Express 4.x中使用bodyParser: http ://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
使用
app.use(express.json());
app.use(express.urlencoded());
代替。 你的代码的问题是,你将在callback被调用之前返回,所以结果将不会被发送给用户。
将您的代码更改为:
返回res.end(util.inspect({fields:fields,files:files}));
并在最后删除回报。