我正在使用react-native-image-picker
来获取图像详细信息,并尝试在https后端服务器中上传。请求不成功,并引发网络错误。它没有建立与后端服务器的连接。问题与我发送的formdata
有关。如果我错过了,能否请您提供header
和其他信息。
export const postImage = async state => {
let formData = new FormData();
formData.append('image', {
uri : state.photo.uri,
type: state.photo.type,
name : state.photo.fileName
});
const config = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: "application/x-www-form-urlencoded",
'Accept': 'application/json'
},
};
try {
return $http.post('/image/save', formData, config)
.then(response => response)
.catch(error => error)
} catch(error) {
console.log(error)
}
}
环境: -Axios版本^ 0.19.2 -其他库版本[React 16.11.0,React Native 0.62.1]
答案 0 :(得分:1)
鳍状肢存在问题,将其升级到0.39.0及以上版本即可
此问题正在此处跟踪:https://github.com/facebook/react-native/issues/28551
修正:https://github.com/facebook/flipper/issues/993#issuecomment-619823916
This should be fixed in version 0.39.0. To upgrade, edit android > gradle.properties
# Version of flipper SDK to use with React Native
FLIPPER_VERSION=0.39.0 // edit this manually
答案 1 :(得分:1)
确保MIME类型与您要上传的文件匹配。 对我来说,这就是问题所在。
答案 2 :(得分: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 文件中
我评论了 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));
答案 3 :(得分:0)
这个问题花了我5个多小时来解决。当我终于能够解决问题时,我正要放弃。
我所面临的与您所提到的差不多的问题是,使用expo-image-picker并尝试使用axios
上传文件时出现了NetworkError。它可以在iOS上完美运行,但不能在android上运行。
这就是我解决问题的方式。
这里有两个独立的问题在起作用。假设我们从图片选择器中获取了imageUri
,然后我们将使用以下几行代码从前端上传。
const formData = new FormData();
formData.append('image', {
uri : imageUri,
type: "image",
name: imageUri.split("/").pop()
});
第一个问题是imageUri
本身。假设照片路径为/user/.../path/to/file.jpg
。然后,Android中的文件选择器将imageUri
的值设为file:/user/.../path/to/file.jpg
,而iOS中的文件选择器将imageUri
的值赋予file:///user/.../path/to/file.jpg
。
第一个问题的解决方案是在Android的file://
中使用file:
而不是formData
。
第二个问题是我们没有使用正确的mime类型。它可以在iOS上正常运行,但不能在Android上运行。更糟糕的是,文件选择器程序包将文件的类型指定为“图像”,而没有给出正确的mime类型。
解决方案是在formData
字段的type
中使用适当的mime类型。例如:.jpg
文件的mime-type将是image/jpeg
,.png
文件的mime-type将是image/png
。我们不必手动执行此操作。相反,您可以使用一个非常著名的名为mime的npm软件包。
最终的解决方案是:
import mime from "mime";
const newImageUri = "file:///" + imageUri.split("file:/").join("");
const formData = new FormData();
formData.append('image', {
uri : newImageUri,
type: mime.getType(newImageUri),
name: newImageUri.split("/").pop()
});
答案 4 :(得分:0)
这是鳍状肢的问题。将gradle.properties中的鳍状肢版本升级到0.43.0+,它将得到修复