base64到S3多张图片

时间:2018-09-11 17:28:35

标签: node.js amazon-web-services express amazon-s3

我当前正在使用以下代码将base64字符串上传到AWS S3

buf = new Buffer(req.body.image.replace(/^data:image\/\w+;base64,/, ""),'base64')
var data = {
    Key: String(product._id),
    Body: buf,
    ContentEncoding: 'base64',
    ContentType: 'image/jpeg',
    ACL: 'public-read'
};

s3Bucket.putObject(data, function(err, data){
    if (err) {
        return res.json({
            success: false,
            msg: 'Oops! Something went wrong.' + err
        });
    } else {
        console.log(data);
        var url = "https://s3.eu-central-1.amazonaws.com/bucketname/" + String(product._id);
        product.image = url;
        product.save(function(err) {
            if (err)
                return res.json({
                    success: false,
                    msg: 'Oops! Something went wrong.' + err
                });


            // Return the product
            res.json({
                success: true,
                product: product
            });
        });
    }
});

这仅适用于仅将一个图像上传到AWS S3平台。现在,我们对应用程序进行了更改,这意味着我们要上传多个图像,因此服务器将收到一组base64图像。将这些文件上传到AWS S3平台的最佳方法是什么?我无法弄清楚。

1 个答案:

答案 0 :(得分:0)

我假设您使用的是AWS javascript SDK,很遗憾,您可能知道s3 putObject仅支持为每个HTTP请求上传一个对象。

我将通过使用Promise并行发送多个请求来加快图像的上传速度。

带有一些未经测试的代码的示例:

const promises = images.map(img => s3Bucket.putObject({
      Key: img._id,
      Body: new Buffer(img.replace(/^data:image\/\w+;base64,/, ""),'base64'),
      ContentEncoding: 'base64',
      ContentType: 'image/jpeg',
      ACL: 'public-read'}).promise());

Promise.all(promises)
    .then(data => {
        console.log(data); // this should be an array of resolved s3 put object promises now
        // you probably want to update your product model accordingly here, I'm just copying your existing code
        var url = "https://s3.eu-central-1.amazonaws.com/bucketname/" + String(product._id);
        product.images = url;
        product.save(function(err) {
          if (err) {
            return res.json({
              success: false,
              msg: 'Oops! Something went wrong.' + err
            });
          }
          // Return the product
          return res.json({
            success: true,
            product: product
          });
    })
    .catch(error => {
        //handle the error in case one of the promises gets rejected
        return res.json({
            success: false,
            msg: 'Oops! Something went wrong.' + err
        });
    });
});