Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How can I read remote image URL as DataURL using FileReader() ?

I have tried but the result is always as bellow:
Please help !

"data:image/jpeg;base64,W29iamVjdCBIVE1MSW1hZ2VFbGVtZW50XQ=="

Bellow is my code:

<script>
function loadFileAsURL() {
var x = new Array();
var img = x[0] ;
img = new Image();
img.src = "https://dl.dropboxusercontent.com/s/2z1e5pcopb2g4vl/raima.jpg" ;

if (img)
var myFILE = new Blob([img], {type:'image/jpeg'});
var target = myFILE ;
var fileReader = new FileReader();

fileReader.onerror = function() {
document.getElementById("encoded").value = "Corrupted file. So conversion is not possible !!! Try another one. Ok ! "; };

fileReader.onprogress = function() {
document.getElementById("encoded").value = "Conversion is in progress... ..."; };

fileReader.onload = function(event) {
var textArea = document.getElementById("encoded");
textArea.innerHTML = event.target.result;};

fileReader.readAsDataURL(target);
}
</script>

<button type="button" >Convert File As Base64 DataURL</button>
<textarea id="encoded" rows="85" cols="100%" wrap="soft" ></textarea>
Posted
Comments
Sergey Alexandrovich Kryukov 16-Jul-15 1:35am    
What are you going to do with the image file?
—SA

1 solution

No, FileReader is not designed to read remote resources via URL. Please see:
https://developer.mozilla.org/en-US/docs/Web/API/FileReader[^],
http://www.javascripture.com/FileReader[^].

To read remote resource, you will need to use Ajax: https://en.wikipedia.org/wiki/Ajax_%28programming%29[^].

One very convenient way to do so would be using jQuery Ajax. See, for example, this article: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax[^].

But, most importantly, see my comment to the question. It all depends on what you want to do with the resource you read.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900