在NodeJS中将Jimp-module与Amazon AWS S3相结合

时间:2018-04-09 18:56:46

标签: node.js amazon-s3

以下我想要实现:

  1. 将图片上传到我的后台
  2. 调整此图片大小以减小图像尺寸。
  3. 将此图片上传到Amazon AWS S3。
  4. 我无法弄清楚如何将图片直接存储到Amazon AWS S3,因此我首先将其上传到我的后台。

    我的代码:

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

    然而,当我运行此代码时:文件被上传到我的后台并正确裁剪,但在Amazon AWS S3中它显示大小为'0 B'。

    如果我删除了行data.resize(400, Jimp.AUTO).quality(100).write(uploadpath),那么该文件会正确上传到Amazon AWS S3,但当然图片不会缩小。

1 个答案:

答案 0 :(得分:0)

您可以使用write回调来保证在上传开始之前写入文件。

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