将图像从 React Native 上传到 AWS 预签名 URL [英] Upload image to AWS presigned URL from react native
问题描述
我正在尝试将图像上传到 AWS Presigned url.我可以获得预先签名的 url,然后我可以从 Postman 上传图像,但我尝试从 React Native 应用程序发送,只发送 uri 信息(content://media/external/images/media/108721).我尝试了很多东西,但我做不到.你能帮我吗?
im trying to upload an image to AWS Presigned url. I can get presigned url then i can upload an image from Postman, but i try to send from React Native application, just uri info is sent (content://media/external/images/media/108721). I tried a lot of thing but i cant do it. Could you help me please?
我正在使用 react-native-image-picker 来选择图像.
I am using react-native-image-picker to select an image.
showImagePicker = () => {
const options = {
title: 'Profile Picture',
storageOptions: {
skipBackup: true,
path: 'images',
base64: true,
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
const avatarData = response;
let presignedUrl = "mypresignedurl";
const xhr = new XMLHttpRequest()
xhr.open('PUT', presignedUrl)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('Image successfully uploaded to S3')
} else {
console.log('Error while sending the image to S3', xhr.responseText)
}
}
}
xhr.setRequestHeader('Content-Type', response.type)
xhr.setRequestHeader('content-lenght', response.fileSize)
xhr.send(response.uri);
this.setState({
avatarSource: source,
avatarData: avatarData,
imageModalVisibilty: true
});
}
});
}
我看到很多这样的例子,但我只发送 uri 字符串.
I saw many example like this but i just only send uri string.
推荐答案
我用另一种方式解决了这个问题.我必须获得 blob 数据 :)
I solved this issue with another way. I had to get blob data :)
export const getBlob = async (fileUri) => {
const resp = await fetch(fileUri);
const imageBody = await resp.blob();
return imageBody;
};
export const uploadImageNew = async (uploadUrl, data) => {
const imageBody = await getBlob(data);
return fetch(uploadUrl, {
method: "PUT",
body: imageBody,
});
};
这篇关于将图像从 React Native 上传到 AWS 预签名 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!