Tanwer
Tanwer

Reputation: 1583

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

Upvotes: 18

Views: 85198

Answers (3)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9774

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);
   };
}

Upvotes: 41

Suhas Mandumale
Suhas Mandumale

Reputation: 95

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");
        }
    }   

Upvotes: 2

user6299088
user6299088

Reputation:

Read image as base64 :

  selectFile(event){
      var files = event.target.files;
      var file = files[0];

    if (files && file) {
        var reader = new FileReader();

        reader.onload =this.handleFile.bind(this);

        reader.readAsBinaryString(file);
    }
  }



  handleFile(event) {
     var binaryString = event.target.result;
            this.base64textString= btoa(binaryString);
            console.log(btoa(binaryString));
    }


***********************************************************************************

OR

Alternate use NPM packge :

https://www.npmjs.com/package/alife-file-to-base64

install : npm install alife-file-to-base64 --save

Add Dependecy to your project

Import AlifeFileToBase64Module to your project and include module in imports section

import { AlifeFileToBase64Module } from 'alife-file-to-base64';

@NgModule({
  declarations: [
  ],
  imports: [
    AlifeFileToBase64Module
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Syntax to use anywhere in your project:

<input type="file" alife-file-to-base64 (onFileChanged)="onFileChanges($event)" [(fileModel)]="files" />
  • onFileChanged : Will get called when file will get selected by user. It will contain filename, filesize,type and base64.
  • fileModel : To set the value of component variable

Upvotes: 1

Related Questions