formidable根据文档,form.multiples = true; 我并没有得到预期的[ files ]
所以,写了以下的处理方式: 把所有http请求字段、上传文件合并到一个列表:
{ 'name' : 'lili', 'phone' : '12345600000', 'upload_one' : { '1.gif' : { ..., name:'1.gif', path:'/home/aa/tmp/2190eq0919.gif', ... }, '2.txt' : {...}, ... }, 'upload_two' : { '11.gif' : { ..., name:'1.gif', path:'/home/aa/tmp/2190eq0919.gif', ... }, '21.txt' : {...}, ... },}
var utility = require('utility'), find = require('./find'), http = require('http'), path = require('path'), fs = require('fs'), fd = require('formidable');function connect (routes, conf, cons) { return function (req, res) { var fif = new fd.IncomingForm(), ffiles = {}, route; // 路由处理器 fif.keepExtensions = true; // 保留扩展名 fif.uploadDir = conf.ldir.tmp; // 上传临时目录 fif.on('file', function(name, file) { if (typeof ffiles[name] !== 'object' || ffiles[name] === null) { ffiles[name] = {}; } ffiles[name][file.name] = file; }); fif.parse(req, function (err, fields, files) { res.req = req; // utility.merge为合并函数, 将多个对象合并,类似jQuery的extend // 不再列出 req.body = utility.merge(fields, ffiles); // 路由处理函数查找,可能每个人写法都不一样 route = find(routes, req.headers.host, req.url, req.method); if (typeof route.handler === 'function') { route.handler(req, res, conf, cons); } else { // 404处理 } }); };}module.exports = connect;
var ffiles = {};fif.on('file', function(name, file) { if (typeof ffiles[name] !== 'object' || ffiles[name] === null) { ffiles[name] = {}; } ffiles[name][file.name] = file;});
ffiles组装完后是这样的:
{ 'upload_one' : { '1.gif' : {..., 'name':'1.gif', path:'...', type:'...', ...}, '2.txt' : {...} }}
然后将ffiles附到req.body,提升使用范围.
req.body.upload_one['1.gif'].name 获取文件名req.body.upload_one['1.gif'].type 获取文件类型req.body.upload_one['1.gif'].path 获取文件上传磁盘路径
...
其他查看console.log(req.body)
联系客服