18

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

3 Answers 3

42

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);
   };
}
Sign up to request clarification or add additional context in comments.

6 Comments

Instead of console.log how can I get this base64 into model property
You can assign the base64 content to model object for API submission. updated the code
thats the problem , model object is not available inside reader.onload function as suggested by you
After Few Changes it worked - "reader.result.toString().split(',')[1]" , Thanks
one question here , will it work if JavaScript is disabled in browser ?
|
2

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

2 Comments

From where this come ? "this.Image " Where is this declaration ?
declare image as Image: string = '';
1

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

3 Comments

try this to getbinary file
check this answer
I will try your second option , NPM Package too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.