【问题标题】:Combine Jimp-module with Amazon AWS S3 in NodeJS在 NodeJS 中将 Jimp-module 与 Amazon AWS S3 结合使用
【发布时间】:2018-04-10 05:39:02
【问题描述】:

以下我想要实现的:

  1. 上传图片到我的后台
  2. 调整此图片的大小以减小图片大小。
  3. 将此图片上传到 Amazon AWS S3。

我不知道如何将图片直接存储到 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)这一行,那么文件会正确上传到亚马逊AWS S3,但图片当然不会缩小。

【问题讨论】:

  • 你有没有想过这个问题?我也有同样的问题

标签: node.js amazon-s3


【解决方案1】:

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

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

【讨论】:

  • 当我实现这个解决方案时,请求并没有结束并最终显示这个错误:'RequestTimeout: Your socket connection to the server was not read from or write to in timeout period.空闲连接将被关闭。
  • 您是否调用 res.send() 将响应发送回您的客户?
猜你喜欢
  • 1970-01-01
  • 2014-01-01
  • 2016-03-04
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多