简体   繁体   English

尝试使用 fetch 从浏览器通过 signedUrl 上传图像 S3,但图像在 s3 中为空白

[英]Trying to upload an image S3 via a signedUrl from a browser using fetch but the image is blank in s3

My backend is a nodejs application and I want users to upload images to an S3 bucket using an S3 signedUrl.我的后端是一个 nodejs 应用程序,我希望用户使用 S3 signedUrl 将图像上传到 S3 存储桶。

From my server I am running:从我的服务器运行:

const s3 = new AWS.S3({ params: { Bucket: bucket }});

app.get('/api/images/signed-url', authMiddleware, (req, res) => {
  s3.getSignedUrl('putObject', 
    { ContentType: 'image/jpeg', Key: uuid() + '.jpeg' }, 
    (_err, url) => res.send({ signedUrl })
})

Then from my browser client I upload to that endpoint然后从我的浏览器客户端上传到该端点

document.querySelector('input[type="file"]').onchange = async (event) => {
  const { signedUrl } = await fetch('/api/images/signed-url').then(res => res.json())

  const target = event.target
  const file = target.files[0]
  const reader = new FileReader()

  reader.onload = async (event) => {
    event.target.value = null

    await fetch(signedUrl, {
      method: 'PUT',
      body: event.target.result,
      headers: {
        "Content-Type": "image/jpeg"
      }
    })
  }

  reader.readAsText(file)
}

I get a 200 and the image is in S3 however the file in S3 is a tiny 10x10 white box.我得到一个 200,图像在 S3 中,但是 S3 中的文件是一个 10x10 的小白框。 Can I get some help on what I am doing wrong?我能得到一些关于我做错了什么的帮助吗?

...almost right, just don't use the filereader, send the blob/file directly in body ...几乎正确,只是不要使用文件阅读器,直接在正文中发送 blob/文件

  const target = event.target
  const file = target.files[0]

  await fetch(signedUrl, {
    method: 'PUT',
    body: file,
    headers: {
      "Content-Type": "image/jpeg"
    }
  })

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

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