Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANGULAR 4 Base64 Upload Component

I am new to Angular. I am using Angular 4. Where there is a requirement to send the base64 Image as one of the model member to the web api. Is there a Angular component or directive for the that would bind the base64 to the said model?

Appreciate and Thank you for the help.

like image 370
Vijayavel Avatar asked Jan 11 '18 21:01

Vijayavel


People also ask

How to build an angular file upload component?

In order to build an Angular file upload component, we need to first understand how to upload files in plain HTML and Javascript only, and take it from there. The key ingredient for uploading files in a browser is a plain HTML input of type file:

How to convert images and Docs to Base64 string in angular?

In Angular application where data is sent via HTTP calls, we can easily convert images and docs to the Base64 string and send them to the server is using HTTP Post. After getting the Base64 string we can easily convert it to a real file and save at server disk with file name and path saved in the database.

What is the file upload component?

The file upload is an essential component to make a form that store some image kind of data. It helps in applications using image upload or in the file sharing. This file-upload component uses file.io API for uploading file and in return it provides a shareable link.

Which version of angular is this post compatible with?

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12 Uploading media files like profile images or PDF or Word documents to the server via a web form is a common practice in data-centric applications.


1 Answers

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

onSubmit(){
    const file = this.DataURIToBlob(this.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

    this.dataService.setProfileImage(formData). //send formData in body
}

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 150
DINESH Adhikari Avatar answered Oct 04 '22 21:10

DINESH Adhikari