Express.js / Multer。在onFileUploadComplete完成之前发送响应

时间:2015-09-30 08:41:17

标签: javascript express multer

我正在使用以下内容进行文件上传服务:

onFileUploadStart: function (file) {
        uploadPath = "";
        imageDimensions = null;
        console.log(file.originalname + ' is starting to upload...');
    },
onFileUploadComplete: function (file) {
        uploadPath = file.path;
        uploadPath = uploadPath.replace(/\\/g,"/");
        console.log("Upload complete. " + file.fieldname + ' uploaded to  ' + file.path)
        sizeOf(file.path, function (err, dimensions) {
            if (err){
                console.log("ERROR, Can't get size of image! " + err);
                return;
            }
            else{
                imageDimensions = { 
                    width : dimensions.width,
                    height: dimensions.height
                };
                console.log("Size of image: width: " + imageDimensions.width + ". height: " + imageDimensions.height);
            }

        });
    }

app.post('/imageupload',function(req,res){
  upload(req,res,function(err) {
    console.log("response is being send..");
    if(err) {
        return res.end("Error uploading file.");
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.json({
        dimensions: imageDimensions,
        path: uploadPath
    });
});

});

根据我的理解(https://stackoverflow.com/a/30458411/2742995)onFileUploadComplete首先在.post处理程序执行之前处理。但是,我的控制台显示:

a.jpg is starting to upload...
Upload complete. file uploaded to uploadeddata\a1235412.jpg
response is being send..
Size of image: width: 2835, height: 1654

所以看起来正好在onFileUploadComplete函数的中间,.post处理程序已经被激活了。

我有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

好的是啊得到了...我使用的sizeOf函数是异步.....

var dimensions = sizeOf(file.path);

是已同步的版本。