Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: 'multer' file upload callback function

Tags:

node.js

multer

I am using 'multer' plugin for file upload. I want to call another function after file upload successfully.

Here my code:

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 want to call my new function after image uploaded. Using this code i can upload image successfully, but not get call callback function.

I need call new function after image uploading completed.

//I need to call this function after image fully uploaded
var uploadSuccessFn = function () {
    //code 
}
like image 447
Hardik Mandankaa Avatar asked Apr 24 '17 08:04

Hardik Mandankaa


2 Answers

You could maybe change the code to use 2 functions in your POST handler:

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

Then simply require the file and use it in the post request handler:

.
.
var imageUpload = require('./handler');

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

.
.
like image 180
bitanath Avatar answered Oct 06 '22 06:10

bitanath


The function (inside the process) when you are calling the process of upload, is the callback fuction just use it . you are written line console.log it means your callback fuction is called when your file is upload but you are not using ..

can be done like this:-

function(req,res){  //callback function
res.json({message:"file uploaded successfully"});
}

it will give you json response.

like image 40
hardy Avatar answered Oct 06 '22 06:10

hardy