简体   繁体   中英

Combine Jimp-module with Amazon AWS S3 in NodeJS

The following I want to achieve:

  1. Upload a picture to my backoffice
  2. Resize this picture to reduce image-size.
  3. Upload this picture to Amazon AWS S3.

I couldn't figure out how to directly store the picture to Amazon AWS S3 and therefore I upload it first to my backoffice.

My code:

router.post('/fileupload', function(req, res){

  // Prepare data
  var file = req.files.upfile;
  var uploadpath = 'profilepicture/' + req.session.user + '.jpg';
  var AWS = require('aws-sdk');
  var fs = require('fs');
  AWS.config.update({
    accessKeyId: **,
    secretAccessKey: **
  });

  // Upload file
  file.mv(uploadpath,function(err){
    if (err) throw err;

    // Read in the file, convert it to base64, store to S3
     Jimp.read(uploadpath, function (err, data) {
       if (err) throw err;

       // Reduce size
       data.resize(400, Jimp.AUTO).quality(100).write(uploadpath);

       var s3 = new AWS.S3();
       var stream = fs.createReadStream(uploadpath);

       s3.putObject({
           Bucket: bucketAmazon,
           Key: req.session.user + '.jpg',
           ContentType: 'image/jpg',
           Body: stream,
           ContentEncoding: 'base64',
           ACL: 'public-read',
           Metadata: {
             'Content-Type': 'image/jpeg'
           }
         }, function (resp) {
           console.log(arguments);
           console.log('Successfully uploaded package.');
           return res.render('settings', {
             user: req.session.user,
             logged: true,
             wrongPicture: false
           });
       });
    });
  });
});

However, when I run this code: the file is uploaded to my backoffice and cropped correctly but in Amazon AWS S3 it shows that the size is '0 B'.

If I remove the line data.resize(400, Jimp.AUTO).quality(100).write(uploadpath) , then the file is uploaded correctly to Amazon AWS S3, but ofcourse the picture is not reduced.

You can use the write callback to guarantee that the file is written before the upload starts.

...
data.resize(400, Jimp.AUTO).quality(100).write(uploadpath, () => {
    // upload to s3 code here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM