Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload Base64 data to a server using formdata React native?

I have an image in Base64 format. I want to send it to the API using formdata. How can that be achieved? I am using React native signature canvas to get the Base64 of the signature.

let signature = base64signature;
const formdata = new FormData();
formdata.append('attachments', {
  uri: signature,
  name: 'logo',
  filename: 'logo',
  type: 'image/png',
});

I followed this link as well but don't understand how to send it to the API as formdata. It's constantly giving network errors.

I have also tried to convert it to a blob and send but that didn't work either. Can anyone help me with this?

like image 384
Yus Avatar asked Sep 05 '25 03:09

Yus


1 Answers

var imgBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCA..." //your bse64 image

onSubmit(){
const file = DataURIToBlob(imgBase64)
const formData = new FormData();
formData.append('upload', file, 'image.jpg') 
formData.append('profile_id', this.profile_id) //other param
formData.append('path', 'temp/') //other param
}

    function DataURIToBlob(dataURI: string) {
        const splitDataURI = dataURI.split(',')
        const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
        const mimeString = splitDataURI[0].split(':')[1].split(';')[0]

        const ia = new Uint8Array(byteString.length)
        for (let i = 0; i < byteString.length; i++)
            ia[i] = byteString.charCodeAt(i)

        return new Blob([ia], { type: mimeString })
      }
like image 138
Code Lover Avatar answered Sep 07 '25 23:09

Code Lover