react-nativereact-native-camerareact-native-image-pickerrn-fetch-blob

How to read image as binary/blob in reactnative


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.


Solution

  • Capture image using 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);
      });
    

    Uploading image

    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) => {
            })