Search code examples
node.jsamazon-web-servicesamazon-s3multer

How to upload image on aws server using node


I am trying to upload the image on the AWS server using the multer using the following code:

//post request
var multer = require('multer');
var upload = multer({  dest: path.resolve('./public/uploads/'), });

/* POST saveblog router. */
router.post('/uploadMedia', upload.any(), function(req, res, next) {

 //console.log("res",res);
 console.log(req.body, 'Body');
 console.log(req.files, 'files');

  var myJSON = JSON.stringify(req.files[0].filename);
  console.log("file name "+myJSON);

  if (typeof myJSON != 'undefined'){
    var obj= new Object();
    obj.status=true;
    obj.message="File Uploaded Successfully";
    obj.type= req.files[0].mimetype;

    var fileExtensionArray=(req.files[0].mimetype).split("/");
    var fileExtension=fileExtensionArray[1];



    res.json(obj);
  }else {
     var obj= new Object();
     obj.status=false;
     obj.message="Error while uploading file try again";

     res.json(obj);
   }

  res.end();
});

It is working fine on the local. But when I upload that code to the server and try to hit through the API. The server stops with following logs

Change detected on path public/uploads/b690b296bfde62eb8ff527328bc8b463 for app www - restarting
PM2        | Stopping app:www id:0

As log says change detected but I am not able to find any image.

As I have searched on StackOverflow and google, I am not able to find tutorial or help to do the same. I am getting help regarding the s3 but I don't want to upload on it.

Is it not possible to upload the image to AWS server like that and I have to use S3 or something wrong with my code?

Edit: Now I am able to get the image to the destination folder but still not able to return the response.


Solution

  • You're likely running PM2 in Watch mode, which is a feature intended to be used in development, to restart your application upon changes to its files. This is not intended to be used in production.

    To fix this, if you're starting pm2 from the cli use the option

    --no-autorestart

    or the yaml config;

    autorestart: false