如何在node.js中使用express来更改上传path

其实我碰到两个问题

首先,如何更改上传path

我的文件夹结构是这样的:

|__app.js |__upload 

我的节点代码是在app.js并从它启动,所以我想上传图片上传到上传文件夹,我改变了path:

 var form = new formidable.IncomingForm; form.uploadDir = "./upload"; 

它似乎上传成功,但我不知道文件在哪里去,它不在上传文件夹。

那么什么是正确的path名?

第二个问题是

如果我不改变它,它可以正确C:/Users/ADMINI~1/AppData/Local/Temp传到C:/Users/ADMINI~1/AppData/Local/Temp但是它将被重命名而没有方格,

那么我怎样才能获得上传格式,并自己更名?

第三个问题是

我也绑定处理程序的process事件,像

 form.on('progress', function(bytesReceived, bytesExpected) { console.log(bytesReceived + ' ' + bytesExpected); }); 

但似乎不起作用,当上传日志没有任何东西。 为什么?我错过了什么?

这是我的所有代码:

 app.post('/upload', function (req, res) { var form = new formidable.IncomingForm; // form.uploadDir = "./upload"; console.log(form.uploadDir); form.parse(req, function(err, fields, files){ if (err) return res.end('You found error'); console.log(files.image); }); form.on('progress', function(bytesReceived, bytesExpected) { console.log(bytesReceived + ' ' + bytesExpected); }); form.on('error', function(err) { res.writeHead(200, {'content-type': 'text/plain'}); res.end('error:\n\n'+util.inspect(err)); }); // res.end('Done'); res.send("well done"); return; }) 

首先,你必须告诉你的应用程序,你不希望bodyParser处理file upload。

 app.use(express.bodyParser()); 

相当于

 app.use(express.json()); app.use(express.urlencoded()); app.use(express.multipart()); 

删除最后一行来处理file upload自己。 初始化表单时添加一些自定义选项

 var form = new formidable.IncomingForm({ uploadDir: __dirname + '/tmp', // don't forget the __dirname here keepExtensions: true }); 

现在你的代码应该工作。