简体   繁体   中英

Best way to get base64 of image angular or node

I want to get the base64 data of the images. I am working in angular 6 as Frontend and NodeJS as backend. From where should I get the base64 string? Either it is computed on frontend or I have to convert it on the backend and then send it back to the frontend? And what is the best way to get the base64 data on frontend as well as on the backend

You can convert into base64 on both angular and nodejs. Depends on the requirement. If you have flexibility to convert on either side, I will suggest you to go with nodejs. If you try on angular,this conversion will be done on browser, where browser might be opened on low end machine, and some file api are specific to browser. Filereader or FIleonload will take more time if the file size is too much.

But, where as most of the server will be hosted in high end machine, it will increase performance as well as it solve the over head of handling browser compatability.

You can get the base64 by below Code in ClientSide angular

handleFileSelect(evt){
      var files = evt.target.files;
      var file = files[0];

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

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

        reader.readAsBinaryString(file);
    }
  }



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

You can convert the image on both the front-end and backend. If you don't need to store the image, then it is better to convert it on frontend. Otherwise, if you are going to store the image to the base64 format, then you can convert it on server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM