Node.js + Express中的表单上传(通过multiparty)

时间:2013-12-23 00:02:34

标签: node.js file-upload express

这是app / routes / index.js中的上传方法:

exports.uploadFile = function(req, res) {
var multiparty = require('multiparty');
var gm = require('gm');
var fs = require('fs');
var form = new multiparty.Form();
var size = '';
var fileName = '';
form.on('part', function(part){
    if(!part.filename) return;
    size = part.byteCount;
    fileName = part.filename;
});
form.on('file', function(name,file){
    console.log(file.path);
    console.log(__dirname);
    console.log('filename: ' + fileName);
    console.log('fileSize: '+ (size / 1024));
    var tmp_path = file.path
    var target_path = __dirname + '/uploads/fullsize/' + fileName;
    var thumbPath = __dirname + '/uploads/thumbs/';
    fs.renameSync(tmp_path, target_path, function(err) {
        if(err) console.error(err.stack);
    });
    res.redirect('/uploads/fullsize/' + fileName);
        console.log(target_path);
    /*gm(tmp_path)
        .resize(150, 150)
        .noProfile()
        .write(thumbPath + 'small.png', function(err) {
            if(err) console.error(err.stack);       
        });*/
});
form.parse(req);

};

我将此方法从app.js称为

app.post('/uploadFile', routes.uploadFile);

当我从上传表单上传文件时,在控制台中收到此错误消息:

/tmp/9039-1m6kw46.jpg
/home/danyaloff/Development/nodejs/projects/nodetest1/routes
filename: 3D-Background-Wallpapers-HD-Wallpapers-in-HD.jpg
fileSize: 910.255859375

fs.js:543
   return binding.rename(pathModule._makeLong(oldPath),
             ^
   Error: ENOENT, no such file or directory '/tmp/9039-1m6kw46.jpg'
   at Object.fs.renameSync (fs.js:543:18)
   at Form.<anonymous> (/home/danyaloff/Development/nodejs/projects/nodetest1/routes/index.js:25:6)
at Form.EventEmitter.emit (events.js:98:17)
at WriteStream.<anonymous> (/home/danyaloff/Development/nodejs/projects/nodetest1/node_modules/multiparty/index.js:527:10)
at WriteStream.EventEmitter.emit (events.js:117:20)
at fs.js:1596:14
at Object.oncomplete (fs.js:107:15)
23 Dec 03:52:59 - [nodemon] app crashed - waiting for file changes before starting...

但是当我在我的app.js文件中使用上传功能时:

app.post('/uploadFile', function(req, res){
    //my upload function
});
一切都很完美。我的代码中有什么问题? THX!

1 个答案:

答案 0 :(得分:7)

使用后问题解决了:

var target_path = './uploads/fullsize/' + fileName;

而不是

var target_path = __dirname + '/uploads/fullsize/' + fileName;