HTTP POST请求在Android上失败



我正在用React Native开发iOS/Android应用程序,我在Android上得到一个错误。

我正在使用expo-image-picker库https://docs.expo.dev/versions/latest/sdk/imagepicker/

这是在iOS上完美工作的代码:

const prepareResult = await ImagePicker.launchImageLibraryAsync({
quality: 0.5,
capture: true,
aspect: [4, 3],
allowsEditing: true,
allowsMultipleSelection: false,
mediaTypes: ImagePicker.MediaTypeOptions.Images,
});
const androidResult = await ImagePicker.getPendingResultAsync();
const result = androidResult?.length ? androidResult[0] : prepareResult;
if (!result.cancelled) {
const localUri = result.uri;
const filename = localUri.split("/").pop();
const match = filename ? /.(w+)$/.exec(filename) : "";
const type = match ? `image/${match[1]}` : `image`;
const formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
fetch(`${API}/uploadAvatar`, {
method: "POST",
headers: {
Authorization: bearer,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
body: formData,
})
.then((response) => response.json())
.then((json) => {
setImage(json.file);
})
.catch((err) => {
console.log({ err });
Alert.alert("There was an error uploading your profile picture.");
});
}

在Android上,当我裁剪图像后,它直接进入.catch方法,甚至没有经过任何.then方法。

我检查了这个https://docs.expo.dev/versions/latest/sdk/imagepicker/#imagepickergetpendingresultasync,其中包含一个注释:

注意:确保你在Android上处理MainActivity销毁。看到ImagePicker.getPendingResultAsync。

对这个错误有什么想法吗?

如果您不是expo项目,而是react-native项目,

建议使用react-native-image-cropicker。

import ImagePicker from 'react-native-image-crop-picker';
//select image
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
}).then(image => {
console.log(image);
});
//select from Camera
ImagePicker.openCamera({
width: 300,
height: 400,
cropping: true,
}).then(image => {
console.log(image);
});

最新更新