【问题标题】:How to use fetch to upload binary file in react native with react-native-image-crop-picker如何使用 fetch 在 react-native-image-crop-picker 中使用 react-native-image-crop-picker 上传二进制文件
【发布时间】:2021-09-28 18:36:16
【问题描述】:

我在上传文件到服务器时遇到了一些麻烦,因为我找不到将 img 转换为二进制数据结构的方法。

这样的成功请求


// upload function 
const UploadImg = async (img: any) => {
  // img  from  react-native-image-crop-picker
  const fromData = new FormData();
  fromData.append('file', `${img.data}`);

  return fetch(`${API_URL_R}/upload`, {
    method: 'POST',
    body: fromData, // this should be binary 
  })
};

// use
// import ImagePicker from  'react-native-image-crop-picker'
 ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true,
      includeBase64: true,
    }).then(async image => {
      await UploadImg(image);
    });



【问题讨论】:

  • 您可以将文件作为Base64发送到服务器。

标签: reactjs react-native react-native-android blob fetch-api


【解决方案1】:

从 ImagePicker.openPicker 中接收到的图像中,您将收到 image.path、image.filename 和 image.mime,然后您可以按如下方式上传图像

注意:文件名也可以作为 让文件名 = path.substring(path.lastIndexOf('/') + 1, path.length)

上传图片

 const UploadImg = async () => {

 const fromData = new FormData();

  fromData.append("file", {
    name: filename,
    type: mime,
    uri:
      Platform.OS === "android"
        ? filepath
        : filepath.replace("file://", "")
  });
 
var url = uploadImageUrl

const response = await fetch(url, {
method: 'POST',
headers: {   
    "Content-Type": "multipart/form-data",
    Accept: "application/json",
    Authorization: authToken
  },
body: fromData, 
})

}

【讨论】:

  • 很高兴能帮到你:)
猜你喜欢
  • 2020-03-13
  • 2021-12-02
  • 1970-01-01
  • 2020-07-17
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2021-01-09
相关资源
最近更新 更多