简体   繁体   English

通过 Put 上传到 S3 时获得有趣的白方块

[英]Getting Fun White Square when Uploading to S3 via Put

Friends, Countrymen, Lend me your ears...朋友们,乡亲们,把你们的耳朵借给我……

I'm signing my url for amazon s3, and then using fileReader and Fetch to put my file in s3.我正在为亚马逊 s3 签署我的 url,然后使用 fileReader 和 Fetch 将我的文件放入 s3。 Though when I do I get a fun white square instead of my image: https://s3.amazonaws.com/hubbble/Gabe/lX4H0.png虽然当我这样做时,我会得到一个有趣的白色方块而不是我的图像: https : //s3.amazonaws.com/hubbble/Gabe/lX4H0.png

const reader = new FileReader();
reader.onload = ((e) => {

  let s3headers = new Headers();
  s3headers.append("content-type", 'image/png');

  fetch(signedRequest, {
      method: 'PUT',
      headers: s3headers,
      body: e.currentTarget.result
  }).then((response)=>{
    console.log(response);
  });
});
  • Permissions Issue?权限问题? Don't really think so as you can definitely view the image不要真的这么认为,因为您绝对可以查看图像
  • Corrupted somehow?不知何故损坏?
  • Maybe an incorrect content type?也许内容类型不正确?

Thoughts?想法? Thanks for any guidance, been banging my head against the wall on this!感谢您的任何指导,我一直在用头撞墙!

The contents of that appear to be a base64 encoded image.其内容似乎是 base64 编码的图像。 That is, you're uploading a text file and not a binary image (and then saying it is, a image/png ) You could just convert it first doing something like this first.也就是说,您正在上传一个文本文件而不是一个二进制图像(然后说它是一个image/png )您可以先将它转换为先做这样的事情

If anyone is coming from a Node environment, the solution is to use the following code.如果有人来自 Node 环境,则解决方案是使用以下代码。 I tested this and it works.我测试了这个并且它有效。 There is no need for atob or doing some bytearray acrobatics.不需要 atob 或做一些 bytearray 杂技。

      // base64DataString is the base64 string, which I assume you have
      // base64Data is a Buffer that is encoded in base64!
      // STEP 1: we remove the header of the dataUri string
      const base64Data = new Buffer.from(b64DataString.replace(/^data:image\/\w+;base64,/, ""), 'base64');


      // STEP 2: CALL PUT OBJECT
      s3.putObject(
        {
          Bucket: "your bucket name",
          Key: `yourfile.jpg`, // the key for S3 location 
          Body: base64Data,
          ContentEncoding: 'base64', // important to tell that the incoming buffer is base64
          ContentType: "image/jpeg", // e.g. "image/jpeg" or "image/png"
          ACL:'public-read'
        },
        (err, data) => {
          if(err) {
            reject(err)
            return;
          }
          console.log("UPLOAD SUCCESSFULLY:") //optional
          console.log(data) //optional
          resolve(data); // if this is in a promise, then include
        }
      )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM