Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Image to base64 string in Typescript

I am trying to post base64 string to my api from Angular 5

First I have to convert it to base64 from image , After checking on internet and MDN I developed a method

  OnIDChange(event) {
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.onloadend = this.handleReaderLoaded.bind(this, "Id");
    reader.readAsBinaryString(file);
  }

And

    handleReaderLoaded(readerEvt:any, indicator: string) {
     var binaryString = readerEvt.target.result;
     if (indicator == "Id") {
       this.Model.IDPhoto = btoa(binaryString);
     }
  }

I have to store this base64 in Model Property to post it in api

But in console it give error "Cannot read property 'result' of undefined" on

var binaryString = readerEvt.target.result;

How can I convert image to base64 , if there is another more suitable way instead of this (any npm package or something else then let me know that too)

Thanks in advance .

Reference from MDN MDN Link

like image 758
Tanwer Avatar asked Nov 03 '18 06:11

Tanwer


People also ask

What is Data Image PNG Base64?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

What is Base64 string?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.


2 Answers

You need to use readAsDataUrl():

function getBase64(event) {
   let me = this;
   let file = event.target.files[0];
   let reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     //me.modelvalue = reader.result;
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}
like image 147
Suresh Kumar Ariya Avatar answered Sep 22 '22 19:09

Suresh Kumar Ariya


This is something i have done to upload a profile picture i have also checked for size less than 512KB and then i have posted that image to my API in next function

i have used FileReader() and readAsDataURL() to convert the file to base64

/* On Change Profile image*/    
    onProfileChange(event:any) {
        if(event.target.files && event.target.files[0]) {
            if(event.target.files[0].type && event.target.files[0].type.split('/')[0] == ["image"] && event.target.files[0].size <= 512000){
                this.file = event.target.files[0];
                var reader = new FileReader();
                reader.onload = (event:any) => {
                    this.Image = event.target.result;
                }
                reader.readAsDataURL(event.target.files[0]);
                this.isBrowser = false;
            } else {
                this.isBrowser = true;
                this._toastr.error("Max image upload size is 500KB only");
            }
        }
    }
    /*end Of On Change profile Image*/


    /*Image api*/
    AddImage(event: any){
        let data=new FormData();
        if(this.file){
            data.append('image',this.file);
            this._db.Post('api/users/image',data).subscribe(b=>{
                if(b.IsResult){
                    this._toastr.success(b.ResultMsg);
                    this.getProfileDetail();
                    this.isBrowser=true;
                }
            });
        }else{
            this._toastr.error("Something went wrong");
        }
    }   
like image 39
Suhas Mandumale Avatar answered Sep 22 '22 19:09

Suhas Mandumale