Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload a base64 encoded image using FormData?

Tags:

I have a jpeg as a base64 encoded string.

var image = "/9j/4AAQSkZJRgABAQEAS..."

I would like to upload this jpeg to the server using FormData.

var data = new FormData();

What is the proper way to append the image to data?

like image 208
user1031947 Avatar asked Oct 31 '14 05:10

user1031947


2 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 177
DINESH Adhikari Avatar answered Sep 28 '22 09:09

DINESH Adhikari


Your image data is nothing more than a string, so append it to your FormData object like this:

data.append("image_data", image);

Then on your server side you can store that directly in a database or convert it to an image and store it on the file system. You might find this post helpful.

like image 30
HeadCode Avatar answered Sep 28 '22 09:09

HeadCode