11

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 
}
4
  • you can use multer as a middleware function : router.post('/image',imageUpload,anotherFunction) Commented Apr 24, 2017 at 8:57
  • You should not be parsing filenames, there is a module for that: path with many builtin functions for that, e.g: path.extname (nodejs.org/api/path.html#path_path_extname_path). Then you should be blocking certain file extensions for security reasons... for a start, all filenames that are executable: .exe, .scr and such. Commented May 12, 2017 at 14:36
  • But i need to call 'var uploadSuccessFn = function () { //code }' This function after image upload successfully. Commented May 13, 2017 at 4:45
  • 1
    you can use the next() function and send the control to anotherFunction(). Commented May 17, 2017 at 13:47

5 Answers 5

3

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

.
.
Sign up to request clarification or add additional context in comments.

3 Comments

Can you provide more details.. is there an error you see? Does the file itself not get uploaded.
using 'module.exports = {uploadFile: uploadFile, afterUpload: afterUpload};' I am not able to call 'uploadFile' function
Yes, you will need to define the two functions in the file as well, just like in the code example above. Did you already add the 2 functions to the file?
1

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.

1 Comment

console.log('Uploade Successful'); This console not print after image uploaded
1

I suggest that you create your own customized storage engine based on multer:

Multer Storage Engine

Then you just add the customized code after your file has been uploaded. Something like this:

MyCustomStorage.prototype._handleFile = function _handleFile (req, file, cb) {
  this.getDestination(req, file, function (err, path) {
    if (err) return cb(err)

  var outStream = fs.createWriteStream(path)

  file.stream.pipe(outStream)
  outStream.on('error', cb)
  outStream.on('finish', function () {

  // Insert here whatever you want to do...
    console.log('Successfully Uploaded');

  cb(null, {
    path: path,
    size: outStream.bytesWritten
  })
}) })}

Please note that you have to use var fs = require('fs') to make it work. Hope this help.

Comments

0

In your code from where you calling upload put an if condition which checks the checks the callback response. If response null then you can call another function in that condition else show some error.

I guess the function you trying call will show some kind of success message to the user.

Comments

0

try like this

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        return cb(null, './Media/ChatDocUpload')
      },
      filename: function (req, file, cb) {
        var _chatMessageID = req.query.chatMessageID;
        var _ext = file.originalname.substring(file.originalname.indexOf("."));
        var _fileName = _chatMessageID + _ext;
         return cb(null, _fileName);
      }
    })

    var upload = multer({ storage: storage })

    module.exports.uploadFile = upload.single('file'), function (req, res, next) {
        console.log('Uploade Successful');
// you function after uploading images
    }

2 Comments

that's work for me i don't why this code not working for u :(
I copy & paste same code in my file, but it is not working. it is not displaying any error. but also not print console log.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.