我有一个flatiron应用程序,现在需要扩展以处理图像的多部分/表单数据上传。
如何处理flatiron应用中的文件上传? union / director似乎忽略了multipart / form-data,而我所有集成强大的尝试都失败了 - 我认为这是因为在formidable获取请求对象之前union会执行的动作。
我尝试过普通和streaming: true
路由,以及before
数组中的原始处理。
我不可能是唯一需要这个的人,所以它可能已被解决,我道歉。我找不到任何参考资料。
答案 0 :(得分:1)
你可以使用与已经使用node-formidable的connect.multipart(或bodyParser)的联合。
var connect = require('connect'),
union = require('union');
var server = union.createServer({
buffer: false,
before: [
connect.bodyParser(),
function(req, res) {
if (req.method==='POST'){
console.log(req.files);
res.end('Done');
}else{
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<form method="post" enctype="multipart/form-data">' +
'<input type="file" name="file" />' +
'<input type="submit" value="Upload" />' +
'</form>');
}
},
]
}).listen(8000);
答案 1 :(得分:0)
显然你必须在Union选项中关闭缓冲,并且在你的端点选项中输入:true:
var fs = require('fs'),
path = require('path'),
union = require('../../lib'),
director = require('director'),
favicon = require('./middleware/favicon'),
// for uploading:
formidable = require('formidable'),
util = require('util');
var router = new director.http.Router();
var server = union.createServer({
buffer: false,
before: [
favicon(path.join(__dirname, 'favicon.png')),
function (req, res) {
var found = router.dispatch(req, res);
if (!found) {
res.emit('next');
}
}
]
});
router.get('/foo', function () {
this.res.writeHead(200, { 'Content-Type': 'text/html' });
this.res.end('<form action="/foo" 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>');
});
router.post('/foo', { stream: true }, function () {
var req = this.req,
res = this.res,
writeStream;
var form = new formidable.IncomingForm();
console.log('Receiving file upload');
form
.on('field', function(field, value) {
console.log(field, value);
})
.on('file', function(field, file) {
console.log(field, file);
})
.on('progress', function(rec, expected) {
console.log("progress: " + rec + " of " +expected);
})
.parse(req, function(err, fields, files) {
console.log('Parsed file upload' + err);
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (err) {
res.end('error: Upload failed: ' + err);
}
else {
res.end('success: Uploaded file(s): ' + util.inspect({fields: fields, files: files}));
}
});
});
server.listen(9090);
console.log('union with director running on 9090');