【发布时间】:2021-11-12 05:21:57
【问题描述】:
我正在使用 Amazon S3 服务通过我的 React Native 应用程序上传图像。 我使用从亚马逊发送的签名 url 来执行上传,所以它是这样工作的:
- 当用户打开相机拍照时,它会向我的服务器发送一个获取请求以获取 url 链接。
- 然后,当用户验证图像时,我使用该签名 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