我使用 fetch 将图像发送到服务器。
在 iOS 上,一切都按预期工作,但在 Android 上,我收到请求失败。
我从 expo 图像选择器获得的 uri,在 IOS 上一切都按预期工作。
const form = new FormData();
form.append('file', {
uri: imageUri,
name: 'file.jpg',
fileName: 'file',
});
fetch(api,{
method: 'post',
body: form,
})
.then(response => response.text())
.then(textResponse => {
console.log(textResponse);
Alert.alert(textResponse);
if (textResponse){
setAccuracyResponse(textResponse);
}
})
.catch(error => {
console.error(error)
});
在 Android 上我得到这个响应
Network request failed
- node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:130:14 in _callTimer
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:383:16 in callTimers
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:416:4 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:109:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:364:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
世博 SDK v39
博览会版本3.28.5
节点 v14.15.0
npm 6.14.8
最佳答案
这有几个问题。首先是 android 中的文件选择器会将 imageUri 值指定为
file:/user/.../path/to/file.jpg
而 iOS 中的文件选择器会将 imageUri 值指定为
file:///user/.../path/to/file.jpg.
所以正确的做法是在android中的formData中使用file://而不是file:。
第二个问题是在表单数据中提供正确的 mime 类型,例如:.jpg 文件的 mime 类型为 image/jpeg,.png 文件的 mime 类型为 image/png,因此您可以使用“mime”npm为此的包。 所以我的最终解决方案如下所示:
const imageUri = result.uri;
const newImageUri = Platform.OS === "android" ? "file:///" + imageUri.split("file:/").join("") : imageUri;
const form = new FormData();
form.append('file', { //this prop can vary depends of your sever settings
uri: newImageUri,
type: mime.getType(newImageUri),
name: newImageUri.split("/").pop(),
});
The complete stack of this problem with a solution can be found here
关于react-native - 在 Android 上的 React Native 博览会上获取图像失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64821291/