1

I use react-native-camera to take a picture and it will save in the mobile like

file:///data/user/0/xxx/cache/Camera/4b1bde90-fa5e-4f91-aac1-029a8b67b3fc.jpg

now I want to upload this image to server and my API scheme is as below

    const formData = new FormData();
    formData.append('file', file); // should be binary, but I don't know how to read image file as binary to here
    formData.append('userId', 1); //
    formData.append('userType', 'normal');

after searched on SO I fund some library rn-fetch-blob and react-native-image-picker but still don't know how to convert image to binary/blob.

4

2 回答 2

1

试试这个,它对我有用

const response = await fetch(pathToImageFile)
const blob = await response.blob()
于 2020-06-22T10:19:50.623 回答
0

使用 react-native-image-picker 捕获图像

launchCamera(options, (response) => {
    console.log('Response = ', response);

    if (response.didCancel) {
      alert('User cancelled camera picker');
      return;
    } else if (response.errorCode == 'camera_unavailable') {
      alert('Camera not available on device');
      return;
    } else if (response.errorCode == 'permission') {
      alert('Permission not satisfied');
      return;
    } else if (response.errorCode == 'others') {
      alert(response.errorMessage);
      return;
    }
    console.log('base64 -> ', response.base64);
    console.log('uri -> ', response.uri);
    console.log('width -> ', response.width);
    console.log('height -> ', response.height);
    console.log('fileSize -> ', response.fileSize);
    console.log('type -> ', response.type);
    console.log('fileName -> ', response.fileName);
    setFilePath(response);
  });

上传图片

const data = new FormData();
data.append("uploadFile", {
    name: filename,
    type: type,
    uri:
      Platform.OS === "android"
        ? fileuri
        : fileuri.replace("file://", "")
  });

  var url = uploadProfilePic

  axios.post(url, data, {headers: {
       
    "Content-Type": "multipart/form-data",
    Accept: "application/json",
    Authorization: authToken

  }})
  .then((res) => {
     
  })
  .catch((err) => {
        })
于 2021-07-20T14:59:35.087 回答