React Native 上传二进制图片

7

我看过使用react-native-fetch-blob上传资产作为表单数据的几个示例,不幸的是,我需要上传到的服务器不支持多部分,而是一个文件的二进制流。我正在使用react native(dettached)并创建了一个本地模块(iOS),它返回要上传文件的本地标识符和本地路径,例如:

4697EAE5-50A3-4462-AE5A-71CC5D08C2D7/L0/001: file:///var/mobile/Media/DCIM/100APPLE/IMG_0038.JPG

然而,当我指定上传的库路径时,它会上传一个空流,并且服务器会存储一个大小为零字节的文件。以下是我当前正在执行的操作示例:

export const uploadFile = (
  action,
  url,
  data,
  showLoading = true,
  showError = true
) => (dispatch, getStore) => { // in the future it's going to be connected to redux
  const uploadPath = RNFetchBlob.wrap(data.replace("file://", ""));
  // uploadPath = "RNFetchBlob-file:///var/mobile/Media/DCIM/100APPLE/IMG_0033.JPG"

  console.log("path to upload", uploadPath);
  return RNFetchBlob.fetch(
    "PUT",
    url,
    {
      // appends the Bearer token of the server
      ...getConfigFromStore(getStore()).headers
      "Content-Type": "application/octet-stream"
    },
    uploadPath
  )
    .then(response => console.log("response ok", response))
    .catch(error => console.error("response error", error));
};

响应是 HTTP 204(因为响应不包含正文),这很好。

另一种选择是获取 base64 字符串数据,但由于手机内存限制并且未来需要支持视频上传,不建议使用,有什么建议吗?


有人能提供这个问题的解决方案吗? - Dulaj Madusanka
1个回答

2
async () => {
    const uri = 'YOUR_IMAGE_URI';
    const response = await fetch(uri);
    const imgBlob = await response.blob();

    return await fetch(SERVER_URL, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/octet-stream',
    },
    body: imgBlob,
  });
}

对于那些好奇的人,我使用react-native-image-picker来选择图像并获取其URI。


请问你能帮我吗? 未定义的对象(在评估“_response.uri”时)。 const response = await fetch(response.uri); const imgBlob = await response.blob(); console.log(imgBlob) - Firas Abu Fares
const response = await fetch(uri) - 我使用react-native-image-picker时,尝试获取uri时返回“读取图像错误[TypeError:网络请求失败]” - Black Beard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接