是否有办法使用Axios或XHR将图像作为二进制数据上传到预先签名的s3 PUT url上

qgelzfjb  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(147)

1)用于生成s3 URL的代码

const file = req.files ? req.files.filename || null : null
      const extension = path.extname(file.name)
      const client = new S3Client()

      const params = {
        Bucket: S3_BUCKET, // env variable
        Key: `tmp/photos/image_file.png`,
        ContentDisposition: 'inline',
        ContentType: file.mimetype,
        Body: file.data
      }

      const command = new PutObjectCommand(params)
      const presignedS3Url = await getSignedUrl(client, command, { expiresIn: 3600 })

我可以使用此CURL请求上载图像

curl --location --request PUT $presignedS3Url \
--header 'Content-Disposition: inline' \
--header 'Content-Type: image/png' \
--data-binary '@/Users/name/Downloads/image-file.png'

无法使用axios上传

const imageFile = fs.readFile('/Users/filepath/image-file.png')
      const bufferString = Buffer.from(imageFile, 'base64')

      await axios.put(presignedS3Url, {
        data: bufferString
      }, {
        headers: {
          'Content-Type': file.mimetype,
          'Content-Disposition': 'inline'
        }
      })

如何使用Axios或XHR上传图像?

tmb3ates

tmb3ates1#

希望这对你有帮助

const fs = require('fs/promises');
  const imageFile = fs.readFile('/Users/filepath/image-file.png')

  await axios.put(presignedS3Url, imageFile, {
    headers: {
      'Content-Type': file.mimetype
    }
  })
4ngedf3f

4ngedf3f2#

在生成预签名URL时使用此

const params = {
        Bucket: S3_BUCKET, // env variable
        Key: `tmp/photos/image_file.png`
      }

若要使用XMLHttpRequest进行上载

const s3Url = uploadedImageResponse?.item?.url || ''
    const xhr = new XMLHttpRequest()
    xhr.withCredentials = false

    xhr.upload.onprogress = event => {
      if (event.lengthComputable) {
        const percentComplete = (event.loaded / event.total) * 100
        progressHandler(percentComplete, fileName)
      }
    }
    xhr.onreadystatechange = async function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          await successHandler(uploadedImageResponse, fileName)
        } else {
          errorHandler('Error uploading file', fileName)
        }
      }
    }
    xhr.open('PUT', s3Url)
    xhr.send(file.file)

相关问题