react-native - 在 Android 上的 React Native 博览会上获取图像失败

标签 react-native expo

我使用 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/

相关文章:

javascript - React-单击按钮时激活下一个选项卡

react-native - 如何使用 Expo 获取 FB Access Token

react-native - React Native FontSize 动画锯齿状

expo - 安装新版本expo-cli@3.26.2时出现很多警告

ios - 世博会上苹果AppTrackingTransparency的问题

react-native - npm install -g expo-cli 未完成安装

javascript - React Native FlatList 错误 -- "Possible Unhandled Promise Rejection (id: 0): undefined is not an object"

javascript - React Native 状态栏禁用 Android

reactjs - 如何处理 redux saga 中的请求数组

animation - 在项目后对 native 动画平面列表项目使用react