节点base64上传到AWS S3存储桶会使图像损坏

时间:2018-07-12 10:11:23

标签: node.js amazon-s3 base64 image-uploading data-uri

我有一个节点路由,该路由应基于data-uri在AWS S3存储桶上上传图像。一切正常,除了图像损坏或未完全上传。

这是我的节点:

router.get('/share', function(req, res, next){

    // Getting the base64 uri from the queried url
    var base64 = req.query.imgUrl;

    // Getting the file type, ie: jpeg, png or gif
    const type = base64.split(';')[0].split('/')[1];

    // Creating a unique key for S3
    const key = uuidv1();

    const buf = new Buffer(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64');
    var params = {
        Bucket: 'myBucket',
        Key: key,
        Body: buf,
        ContentEncoding: 'base64',
        ContentType: `image/${type}`,
        ContentLength: buf.length,
        ACL: 'public-read'
    };

    // Uploading
    s3.putObject(params, function(err, data){
        if (err) { 
            console.log(err);
            console.log('Error uploading data: ', data);
        } else {
            console.log('succesfully uploaded the image!');
        }
    });

    res.send('foo');
});

我在S3上获得的图像:

What a mess...

应该是的图像:

A magnificent dickbutt

1 个答案:

答案 0 :(得分:0)

您的代码说您正在以base-64编码格式对图像进行编码,然后使用aws sdk for nodejs将图像上传到s3。实际上,您实际上使一件简单的事情变得更加复杂,aws sdk会自动以base-64编码格式对图像进行编码,然后将其上传,因此您无需明确地进行操作。

这是一个简单的示例,可以完成您想做的事情:

var file = fileChooser.files[0];
if (file) {
    results.innerHTML = '';


    var params = {
         Bucket: 'mybucket'
         Key: 'dated/group1.jpeg',
         ContentType: 'image/jpeg',
         Body: file,
         ACL: 'public-read'
    };

    s3.putObject(params, function (err, data) {
        if (err) {
            results.innerHTML = 'ERROR: ' + err;
        }else {
            results.innerHTML = ' snapshot uploaded !!!';
         }
            }).on('httpUploadProgress', function (progress) {console.log(progress);});


} else {

            results.innerHTML = 'Nothing to upload.';
  }