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

Jus*_*tin 7 javascript amazon-s3 amazon-web-services

朋友们,同胞们,请听我说……

我正在为 amazon s3 签署我的 url,然后使用 fileReader 和 Fetch 将我的文件放入 s3 中。虽然当我这样做时,我得到一个有趣的白色方块而不是我的图像: 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);
  });
});
Run Code Online (Sandbox Code Playgroud)
  • 权限问题?别这么想,因为你绝对可以查看图像
  • 以某种方式损坏了?
  • 也许内容类型不正确?

想法?感谢您的指导,为此我一直在用头撞墙!

Jac*_*ack 5

其内容似乎是一个 base64 编码的图像。也就是说,您上传的是文本文件而不是二进制图像(然后说它是,a image/png)您可以先将其转换,然后先执行类似的操作

  • 您是一位绅士,也是一位学者。我知道事情一定是这样的。最终按照答案之一的建议使用 fetch 来读取文件。超级简单而且效果很好! (2认同)

KJ *_*Ang 5

如果有人来自 Node 环境,解决方案是使用以下代码。我测试了这个并且它有效。不需要 atob 或做一些字节数组杂技。

      // 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
        }
      )
Run Code Online (Sandbox Code Playgroud)