Tom Cariello
Tom Cariello

Reputation: 117

Node.js upload to Amazon S3 works but file corrupt

I am submitting a form via my CMS which contains a filepicker for an image & some text. The code runs & an object is created in my S3 account with the correct name but it is corrupt. For example, I am uploading JPG images but when I view them in the s3 dashboard I just see a black screen.

Any help is greatly appreciated.

My HTML form:

<form enctype="multipart/form-data" action="updateSchedule" method="POST"> 
        <input type="file" name="schedulepicture" id="schedulepicture">
        <textarea rows="4" cols="50" id="ScheduleText" name="ScheduleText" maxlength="2000">                     <button type="submit" id="updateschedulebutton">Update</button>
</form>

My Node.JS script:

router.post('/updateschedule', isLoggedIn, upload.single('schedulepicture'), function(req, res) {
  var scheduleImageToUpload;

  //Check if image was uploaded with the form & process it
  if (typeof req.file !== "undefined") {

    //Create Amazon S3 specific object
    var s3 = new aws.S3();
   
    //This uploads the file but the file cannot be viewed.
    var params = {
      Bucket: S3_BUCKET,
      Key: req.file.originalname, //This is what S3 will use to store the data uploaded.
      Body: req.file.path, //the actual *file* being uploaded
      ContentType: req.file.mimetype, //type of file being uploaded
      ACL: 'public-read', //Set permissions so everyone can see the image
      processData: false,
      accessKeyId: S3_accessKeyId,
      secretAccessKey: S3_secretAccessKey
     }

    s3.upload( params, function(err, data) {
      if (err) {
        console.log("err is " + err);
      }
      res.redirect('../adminschedule');
    });
  }
});

Upvotes: 2

Views: 2863

Answers (1)

Denis
Denis

Reputation: 2140

I do believe you need to pass a stream instead of the file path, you can use fs.createReadStream like this:

router.post('/updateschedule', isLoggedIn, upload.single('schedulepicture'), function(req, res) {
  var scheduleImageToUpload;

  //Check if image was uploaded with the form & process it
  if (typeof req.file !== "undefined") {

    //Create Amazon S3 specific object
    var s3 = new aws.S3();
    var stream = fs.createReadStream(req.file.path)

    //This uploads the file but the file cannot be viewed.
    var params = {
      Bucket: S3_BUCKET,
      Key: req.file.originalname, //This is what S3 will use to store the data uploaded.
      Body: stream, //the actual *file* being uploaded
      ContentType: req.file.mimetype, //type of file being uploaded
      ACL: 'public-read', //Set permissions so everyone can see the image
      processData: false,
      accessKeyId: S3_accessKeyId,
      secretAccessKey: S3_secretAccessKey
     }

    s3.upload( params, function(err, data) {
      if (err) {
        console.log("err is " + err);
      }
      res.redirect('../adminschedule');
    });
  }
});

Upvotes: 3

Related Questions