Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native upload image as binary

I've seen several examples of uploading a file using react-native-fetch-blob to upload assets as Form data, unfortunately the server that I need to upload to doesn't support multipart but a binary stream of the file. I'm using react native (dettached) and created a native module (iOS) that returns the local Identifier and the local path of the file to upload, for example:

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

however, when I specify the path to the library to upload, it uploads an empty stream and the server stores a zero-bytes size file, I'm uploading a snippet of what I'm doing right now:

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));
};

The response is a HTTP 204 (which is fine since the response doesn't contain a body)

An alternative is getting the base64 string data but it's not recommended due to memory limitations in the phone and I need to support videos upload in the future, any suggestions?

like image 277
Javier P Avatar asked Jan 30 '18 16:01

Javier P


People also ask

How do I send an image in format in react native?

First we initialize FormData , and we then append the photo key. The body of this message is the minimum required to get this working. We need to pass a file name, a file type, and then a uri. The uri is where the image is located on the device.

How do you upload image using multipart in react native?

In the uploadImage() function, create a FormData object and append the image data. Call the axios. post() method to make the POST request to the upload endpoint. In the headers , add Content-Type: multipart/form-data to enable file upload to the server.


1 Answers

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,
  });
}

For those who are curious, I use react-native-image-picker in order to pick an image and get its uri.

like image 124
T. Dayya Avatar answered Oct 27 '22 11:10

T. Dayya