0

I am trying to get base64 of the image in my HTML by using HTML FileReader but for some reasons it doesn't work. My html is:

<div></div>

And script is:

var file = "http://mw2.google.com/mw-panoramio/photos/medium/23830229.jpg";
var reader = new FileReader();
reader.onload = function (e) {
    iconBase64 = e.target.result;
    $('div').append(iconBase64);
}

Can anybody help me?

C1pher
  • 1,933
  • 6
  • 33
  • 52
qqruza
  • 1,385
  • 4
  • 20
  • 41
  • 2
    Unfortunately, you're statement is quite accurate. There are (quite) some reasons. A few are: `FileReader` reads local files, not remote files. You don't do anything with the URL in `file`. Nothing here does any Base64 conversion. You should find some tutorials. – Amit Aug 03 '15 at 21:24
  • http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – lintmouse Aug 03 '15 at 21:32
  • How about a javascript solution? http://jsfiddle.net/handtrix/yvq5y/ – Jacksonkr Aug 03 '15 at 22:31

2 Answers2

2

I'll have to go against the majority and tell that you can actually get it without a canvas.

The statement that FileReader can't read external files is not completely true :
You can give it a blob as source.
So you can convert your external resource to a Blob object, using XMLHttpRequest
making it available from the local machine so the above statement isn't completely false either,
then get its dataURL from the FileReader.

var file = "http://mw2.google.com/mw-panoramio/photos/medium/23830229.jpg";
var xhr = new XMLHttpRequest();
xhr.onload = function(e) {
  getDataURL(this.response);
};
xhr.open('GET', file, true);
// the magic part
xhr.responseType = 'blob';
xhr.send();


function getDataURL(blob) {
  var reader = new FileReader();
  reader.onload = function(event) {
    var dataURL = this.result;
    document.querySelector('img').src = dataURL;
    document.querySelector('p').innerHTML = dataURL;
   };
 var source = reader.readAsDataURL(blob);
}
<img/>
<p></p>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

You can't use FileReader to solve this problem, because you are not trying to read local files (that is the purpose of FileReader)

Just convert the image taken from the web link using something like this answer https://stackoverflow.com/a/20285053/912450

Community
  • 1
  • 1
jperelli
  • 6,988
  • 5
  • 50
  • 85