【问题标题】:File image broken after upload to amazon S3 Bucket上传到亚马逊 S3 存储桶后文件图像损坏
【发布时间】:2021-11-12 05:21:57
【问题描述】:

我正在使用 Amazon S3 服务通过我的 React Native 应用程序上传图像。 我使用从亚马逊发送的签名 url 来执行上传,所以它是这样工作的:

  1. 当用户打开相机拍照时,它会向我的服务器发送一个获取请求以获取 url 链接。
  2. 然后,当用户验证图像时,我使用该签名 URL 发出请求。

这里的问题是文件(jpeg 图像)在亚马逊 S3 中上传后损坏。所以上传工作正常,但我无法打开图像。我尝试使用 Insomnia 并且打开图像效果很好,因此它必须与我通过我的 react- 发送的 formData 正文相关联原生应用。

这是我的组件在 react native 中的代码:

const result = await ImagePicker.launchCameraAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [1, 1],
  });

  if (!result.cancelled) {
    const resizeResult = await ImageManipulator.manipulateAsync(
      result.uri,
      [{ resize: { height: 400, width: 400 } }],
      { format: "jpeg", compress: 0.8 }
    );

    const formData = new FormData();
    formData.append("putObject", {
      uri: resizeResult.uri,
      name: `${infoUser.id}`, // the name here shouldn't matter as it's already defined in the query (but I use the same that has be signed)
      type: "image/jpeg",
    });
    const config = {
      headers: {
        "Content-Type": "image/jpeg", // I also tried : "multipart/form-data" 
      },
    };

    // results.data is the signed url

      axios.put(results.data, formData, config);
       .then((res) => console.log(res))
       .catch((e) => console.log(e.response));

签名网址如下所示:

https://bucketname.s3.eu-west-3.amazonaws.com/profile.jpg?Content-Type=image%2Fjpeg&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUE*******7%2Feu-west-3%2Fs3%2Faws4_request&X-Amz-Date=20210917T094406Z&X-Amz-Expires=900&X-Amz-Signature=a6828c1669*********ffe641b4a&X-Amz-SignedHeaders=host%3Bx-amz-acl&x-amz-acl=public-read

在使用 amazon s3 之前,我使用完全相同的 formData 对象将图像发送到我的服务器,它工作得很好。

谢谢

【问题讨论】:

  • formData 部分看起来不错。我猜 axios PUT 请求有问题。不确定。
  • 使用 Fiddler 捕获和比较请求,您将得到答案。
  • 我刚刚尝试使用 Fiddler,但是当我检查 put 请求时我什么也没看到,我认为是因为 SSL。

标签: javascript reactjs amazon-web-services react-native amazon-s3


【解决方案1】:

经过多次试验,我成功地将图像上传到 Amazon S3,但我真的不知道它是如何工作的。

所以不要使用

const formData = new FormData();

我只是将对象 resizeResult 作为我的正文请求传递。

请求如下所示:

 await fetch(results.data, {
      method: "PUT",
      body: resizeResult,
    })
      .then(() => console.log("success ?"))
      .catch((err) => {
        console.log(err);
      });

resizeResult 在哪里

Object {
  "height": 2112,
  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540yoann84%252FoneTribe/ImageManipulator/95843dca-e89a-4cec-977b-cd2177d71f57.jpeg",
  "width": 400,
}

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2018-01-23
    • 2012-07-07
    • 1970-01-01
    • 2013-05-23
    • 2018-05-21
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多