我是一nodejs新手,老板要求我能用nodejs实现stream方式上传图片,google良久,发现formidable很好用,也很受人们喜爱,然后在google找到许多例子,但是总是实现不了
var form = new formidable.IncomingForm();
form.parse( request, function( error, fields, files ) {
console.log( "Completed Parsing" );
if( error ){
response.writeHead( 500, { "Content-Type" : "text/plain" } );
response.end( "CRAP! " + error + "\n" );
return;
}
}
在这里的时候 总是报错 Error: MultipartParser.end(): stream ended unexpectedly: state = START,在github上有相关问题的讨论,研究良久仍不得其解,望各位帮忙,谢谢。
5 回复
没这么用过,我把我的一个老的例子贴出来,希望有点用。测了一下,还运行正常。
var http = require('http');
var util = require('util');
var formidable = require('formidable');
var TEST_TMP = '/tmp';
var TEST_PORT = 8001;
var server = http.createServer(function(req, res) {
if (req.url == '/') {
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/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>'
);
} else if (req.url == '/upload') {
var files = [];
var fields = [];
var form = new formidable.IncomingForm();
form.uploadDir = TEST_TMP;
form.on('field', function(field, value) {
console.log('field event:', field, value);
fields.push([field, value]);
});
form.on('file', function(field, file) {
console.log('file event:', field, file);
files.push([field, file]);
});
form.on('end', function() {
util.puts('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);
} else {
res.writeHead(404, {'content-type': 'text/plain'});
res.end('404');
}
});
server.listen(TEST_PORT);
util.puts('listening on http://localhost:' + TEST_PORT + '/');