Search code examples
javascriptreact-nativern-fetch-blob

React native upload image as binary using rn-fetch-blob


I am trying to upload an image as binary. I used rn-fetch-blob library for this one. Because normal fetch gives network errors.

const path = file.path.replace('file://', '');
const uploadPath = RNFetchBlob.wrap(path);

RNFetchBlob.fetch(
    'PUT',
      SERVER_URL,
      uploadPath,
  )
    .then(res => {
      console.log('image uploaded res ---> ',res);
    })
    .catch(err => {
      console.log(err);
    });

it uploads an empty stream and the server stores a zero-byte size file. Any solution for this issue?


Solution

  • it uploads an empty stream and the server stores a zero-byte size file. Any solution for this issue?

    This is because it is not able to find the image file at the path specified. Can you please try something like this and let me know ?

      const filePath = Platform.OS === 'ios'
     ? res.path().replace('file:///', '').replace('file://', '')
     : res.path().replace('file://', '').replace('file:/', '');
    
      RNFetchBlob.fetch('PUT', 'your-server-url', {
       // this is required, otherwise it won't be processed as a multipart/form-data request
        'Content-Type' : 'multipart/form-data',
      }, [
        // append field data from file path
        {
          name : 'test',
          filename : 'test.png',
          // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.
          // Or simply wrap the file path with RNFetchBlob.wrap().
          data: RNFetchBlob.wrap(filePath)
        }
      ]).then((resp) => {
        // ...
      }).catch((err) => {
        // ...
      })
    

    Hope it helps