How to upload image as binary in react native

4.1k Views Asked by At

this is from post man

enter image description here

in react native how can i convert image and upload it to server as binary

this is my code i try to use form data insted of header but still not working the upload work but the image not showing

      ImagePicker.showImagePicker(options, async (response) => {
                if (response.didCancel) {
                  setIsLoading(false);
                } else if (response.error) {
                  setIsLoading(false);
                } else if (response.customButton) {
                } else {
                  setIsLoading(true);

               
                  function dataURLtoFile(dataurl, filename) {
                    var arr = dataurl.split(','),
                      mime = arr[0].match(/:(.*?);/)[1],
                      bstr = atob(arr[1]),
                      n = bstr.length,
                      u8arr = new Uint8Array(n);
                    while (n--) {
                      u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new File([u8arr], filename, {type: mime});
                  }

         

          
                  var file = dataURLtoFile(
                    'data:image/png;base64,' + response.data,
                    'hello2.png',
                  );
                  var myHeaders = new Headers();
                  myHeaders.append('type', '1');
                  myHeaders.append('uploadPath', 'xxx');
                  myHeaders.append('Content-Type', 'image/png');
                

                  var requestOptions = {
                    method: 'POST',
                    headers: myHeaders,
                    body: file,
                    processData: false,
                    contentType: false,
                  };

                  fetch(
                    'xxx',
                    requestOptions,
                  )
                    .then((response) => response.json())
                    .then((result) => {

after i upload the image this is how it show

enter image description here

2

There are 2 best solutions below

3
Someone Special On

I don't know why you convert your file to data:String, and try to upload as image/png content-type. Do you want data:string or as the file itself? if you want to use data:String then your content type should be plain/text.

This is what I normally do to upload image.

const uploadImage = async (response) => {
    
    const put = await fetch(url, { method: 'post', body: response, headers: { "Content-type": response.type } });

}

Where response is the response returned by ImagePicker.showImagePicker

Depending on your server, you may require form data, which then you need to do the formData way.

const uploadImage = async (response) => {
    
    let formData = new FormData();
    formData.append('file', response);
     //in most case you do not need to create custom header object.
    const put = await fetch(url, { method: 'post', body: formData });

}

blob method.

const uploadImage = async (response) => {
    
     var blob = new Blob(response);

     //in most case you do not need to create custom header object.
    const put = await fetch(url, { method: 'post', body: blob, header: { 'Content-type": response.type  });

}

Above example is base on a single file selected, if you select multiple file then response will of course be an array instead.

0
LudzPG On

I had the same issue.

I used this function and worked perfectly for me:

{...}
import { readFile } from 'react-native-fs';
import { Buffer } from "@craftzdog/react-native-buffer";
{...}

type AttachmentRollObject = {
  uri: string;
  type: string | null;
  name: string | null;
  attachmentId?: string;
}

const uploadFile = async (file: AttachmentRollObject) => {
  let path = file.uri
  if (isIphone) {
    path = file.uri.replace('file:', '')
  } else {
    path = file.uri
  }

  readFile(path, 'base64')
    .then(contents => {
      const body = Buffer.from(contents, 'base64')

      uploadAttachment({
      contentType: file.type || '',
      contentDisposition: `attachment; filename="${file.name}"`,
      body
    })
  })
  .catch((error) => console.log({ error }))
}