我正在尝试通过使用来上传图像
react-native-image-crop-picker
和axios
所以这是我的代码:
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true,
forceJpg:true,
mediaType:'photo'
}).then( async (image) => {
try {
//console.log(image);
var myImage = {
uri:image.path,
//uri:image.path,
name: 'profile_pic.jpeg',
type: image.mime, // or photo.type
};
//var test = {uri:image.path,type:image.mime,name:'MY_IMAGE'};
let response = await APIUpdateProfile(myImage);
console.log(response);
} catch (error) {
showMessage({
message: error.message,
type: "danger",
titleStyle:{fontSize:18}
});
}
}).catch(() => { });
// from another file
export async function APIUpdateProfile(data){
try{
const options = {
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
const form_data = new FormData();
form_data.append('image', data);
console.log(form_data);
const res = await axios.post(c.UPDATE_PROFILE, form_data,options);
return res.data;
}catch (e) {
console.log(e);
throw handler(e);
}
}
和我的php api标头:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Content-Type: multipart/form-data");
输出
{"_parts": [["image", [Object]]]}
[Error: Network Error]
答案 0 :(得分:1)
更改这一行:form_data.append('image', data);
到 form_data.append('image', JSON.stringify(data));
来自https://github.com/react-native-image-picker/react-native-image-picker/issues/798
您需要将此 uesCleartextTraffic="true" 添加到 android/app/src/main/AndroidManifest.xml 目录中的 AndroidManifest.xml 文件中
<申请 ... android:usesCleartextTraffic="true"> 然后,由于 Flipper Network 的问题。
我评论了 initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
在这个文件中 /android/app/src/main/java/com/{your_project}/MainApplication.java
另外,注释掉这个文件 android/app/src/debug/java/com/**/ReactNativeFlipper.java 中的第 43 行
line43: builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));