我正在使用“multer”插件上传文件。文件上传成功后,我想调用另一个函数。

这是我的代码:

module.exports.uploadFile = upload.single('file', '_id'), function (req, res, next) {
    console.log('Uploade Successful');
}

var upload = multer({
storage: multer.diskStorage({
    destination: './Media/ChatDocUpload',
    filename: function (req, file, cb) {
        var dest = './Media/ChatDocUpload';

        //query string params
        var _chatMessageID = req.query.chatMessageID;

        var _ext = file.originalname.substring(file.originalname.indexOf("."));
        var _fileName = _chatMessageID + _ext;

        cb(null, _fileName);
    }
})
});

我想在图片上传后调用我的新函数。使用此代码,我可以成功上传图像,但不能获取调用回调函数。

图片上传完成后,我需要调用新功能。
//I need to call this function after image fully uploaded
var uploadSuccessFn = function () {
    //code
}

最佳答案

您可以更改代码以在POST处理程序中使用2个函数:

module.exports = {uploadFile: uploadFile, afterUpload: afterUpload};

function uploadFile(){
    upload.single('file', '_id');
}

function afterUpload(req, res, next) {
        console.log('Uploade Successful');
    }


    var upload = multer({
    storage: multer.diskStorage({
        destination: './Media/ChatDocUpload',
        filename: function (req, file, cb) {
            var dest = './Media/ChatDocUpload';

            //query string params
            var _chatMessageID = req.query.chatMessageID;

            var _ext = file.originalname.substring(file.originalname.indexOf("."));
            var _fileName = _chatMessageID + _ext;

            cb(null, _fileName);
        }
    })
    });

然后只需索取文件,然后在发布请求处理程序中使用它即可:
.
.
var imageUpload = require('./handler');

app.post('/image/upload',imageUpload.uploadFile,imageUpload.afterUpload);

.
.

关于node.js - NodeJS : 'multer' file upload callback function,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43583163/

10-12 04:10