multer file upload hangs with express on server but not locally

Viewed 1120

I have been searching a while but not got answer please help

So I want to upload files to server, I have code

var upload = multer({ storage: common.storage , fileFilter : common.fileFilter,limits:{fileSize:config.maxSize} }).array('media');

upload(req, res, function (err) {

    if (err) {

        res.json({'success' : false , 'err' : err ,  msg : 'Something went wrong please try again'});
    }else{

        if(req.fileValidationError) {

            return res.end(req.fileValidationError);
        }`

Its some code to upload file on multer where common.storage function is as

'storage' : multer.diskStorage({
  destination: function (req, file, cb) {

     console.log(req.pathToSaveFile)
     cb(null, 'uploads/' + req.pathToSaveFile)
  },
  filename: function (req, file, cb) {
     console.log('file' , file)
     cb(null, req.timestamp +'_'+ file.originalname)
  },

}),

after console file nothing happens, please help me in this

`

1 Answers

If your server is running with PM2 than its the most common error we got, because of watch here is an example for file upload with node js.

const multer = require('multer');
var storage =   multer.diskStorage({server
  destination: function (req, file, callback) {
    callback(null, 'UPLOAD_FOLDER_PATH');
  },
  filename: function (req, file, callback) {
    callback(null, new Date().toISOString().replace(/[-T:\.Z]/g, "") + file.originalname) ; // toISOString has been used to rename your file.
  }
});

var upload = multer({ storage : storage}).single('YOUR_INPUT_FIELD_NAME');
upload(req,res,function(err) {
  if(err) {
    return res.end("Error uploading file.");
  } else {
    // File uploaded successfully.
    // Do you stuff.
  }

Note : There are two way to use for the following code with PM2

1) Start PM2 server without watch. (Not recommended.)

pm2 start index.js

2) Start PM2 server with watch and ignore file upload folder.

pm2 start index.js --watch --ignore-watch "UPLOAD_FOLDER_PATH"

Happy coding cheers!

Related