【问题标题】:Fetching image fails on expo on react native on android在 android 上反应原生的博览会上获取图像失败
【发布时间】:2020-11-13 12:54:31
【问题描述】:

我使用 fetch 将图像发送到服务器。 在 iOS 上,一切都按预期工作,但在 android 上,我得到 Request fialed。
我从 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)
      });

在安卓上我得到这个响应

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

Expo sdk v39
世博会版本 3.28.5
节点 v14.15.0
npm 6.14.8

【问题讨论】:

  • 嘿,即使我也面临着类似的问题。你有进步吗?
  • @SubhangV 我已经更新了我的答案,请查看下方。

标签: react-native expo


【解决方案1】:

这有几个问题。首先是 android 中的文件选择器会将 imageUri 值设为

file:/user/.../path/to/file.jpg 

而 iOS 中的文件选择器会将 imageUri 值设为

file:///user/.../path/to/file.jpg.

所以正确的做法是在android的formData中使用file://而不是file:

第二个问题是在表单数据中提供正确的 mime 类型,例如:.jpg 文件的 mime-type 为 image/jpeg,.png 文件为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多