base64到S3多个图像

问题描述 投票:0回答:1

我目前正在使用以下代码将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
            });
        });
    }
});

这适用于仅将1个单个映像上载到AWS S3平台。我们现在正在对应用程序进行更改,这意味着我们要上传多个图像,因此服务器将接收的是一系列base64图像。将这些上传到AWS S3平台的最佳方式是什么?我无法弄明白。

node.js amazon-web-services express amazon-s3
1个回答
0
投票

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

我会通过使用promises并行发送多个请求来加速图像上传。

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

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
        });
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.