node.js - Node.js + Express 中的表单上传(通过多方)

标签 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
});

一切都很完美。我的代码有什么问题?谢谢!

最佳答案

使用后问题解决:

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

而不是

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

关于node.js - Node.js + Express 中的表单上传(通过多方),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20735429/

相关文章:

node.js - 从 JSON 创建 TS 类实例时是否可以处理未知属性?

php - 警告 : File upload error - unable to create a temporary file in Unknown on line 0

javascript - Node Js 路由不起作用

node.js - 对于使用 Node js 的 Express JS 应用程序来说,正确的基于 MVC 的目录结构是什么?

node.js - 如何将数据作为整数而不是 NodeJS 中的字符串存储到 MongoDB 中?

AngularJS 和 Express 路由 404

node.js - AWS.Transfer 不是构造函数

iOS Swift 使用 Alamofire 上传 PDF 文件(多部分)

java - 如何在 wicket 中使用 MultiFileUploadField 进行多个文件选择?

javascript - 当我启动 Node.js Express 应用程序时,我有奇怪的代码而不是主页