s3.upload() works but uploads broken image

为君一笑 提交于 2019-12-24 04:43:05

问题


I've got a Lambda function in AWS that is hooked up to a POST method which basically takes an image URL and uploads the image to an S3 bucket.

My Lambda function looks like this:

var s3 = new AWS.S3();

exports.handler = (event, context, callback) => {
  let encodedImage = JSON.parse(event.body).user_avatar;
  let decodedImage = Buffer.from(encodedImage, 'base64');
  var filePath = "avatars/" + event.queryStringParameters.username + ".jpg"

  var params = {
    "Body": decodedImage,
    "Bucket": "MYBUCKETNAME.com",
    "Key": filePath
  };
  s3.upload(params, function (err, data) {
    if (err) {
      callback(err, null);
    } else {
      let response = {
        "statusCode": 200,
        "headers": {
          "my_header": "my_value"
        },
        "body": JSON.stringify(data),
        "isBase64Encoded": false
      };
      callback(null, response);
    }
  });
};

It seems to upload the image to the bucket specified, but when I view the image it seems to be broken.

I'm very inexperienced with using AWS for anything outside of the GUI they provide. If anyone has any idea of what might be going on I'd appreciate any help. Thanks in advance!


回答1:


When uploading an image file you should also specify the content type. For jpeg it is image/jpeg. For png it is image/png. If you leave out content type the image might not display at all (just black space).

Content-Type

There are node.js libraries to figure out the image type for you. This is just one of many such libraries:

image-type

var params = {
  Body: decodedImage,
  Bucket: "MYBUCKETNAME.com",
  Key: filePath,
  Content-Type: 'image/jpeg'
};


来源:https://stackoverflow.com/questions/53998940/s3-upload-works-but-uploads-broken-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!