Convert local URL(URL) to Base64 in javascript

  1. set responseType to Blob ,
  2. use FileReader() at XMLHttpRequest onload event to read response as data URI
var xhr = new XMLHttpRequest();       
xhr.open("GET", "/path/to/local/image/file", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res)
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()

Thanks! Please give a clap if the post is helpful. Write in the comment section for any help or suggestion.

--

--

--

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shivam Gupta

Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

More from Medium

Fetching Script Tags and Attributes from String

What is NVM, and how to use it?

Deep dive into prototype chaining in JavaScript

For… in VS For…of — JavaScript