Upload image to FileReader

I want to upload an image from url to fileryader in order to get the data url of this image. I tried to find a solution on Google, but I can find read-only solutions from file input on the local computer.

+3
source share
1 answer

If you want to use a URI image to use data, I suggest loading the image into a tag <img>, draw it on <canvas>, then use the method .toDataURL()for the canvas.

Otherwise, you need to use XMLHttpRequestblob to get the image (set the property responseTypeto an XMLHttpRequest instance and get the blob from the property .response). Then you can use the API FileReaderas usual.

In both cases, the images must be located on the same origin, or CORS must be included.

If your server does not support CORS, you can use a proxy server that adds CORS headers. In the following example (using the second method), I use CORS Anywhere to get CORS headers in any image I want.

var x = new XMLHttpRequest();
x.open('GET', '//cors-anywhere.herokuapp.com/http://www.youtube.com/favicon.ico');
x.responseType = 'blob';
x.onload = function() {
    var blob = x.response;
    var fr = new FileReader();
    fr.onloadend = function() {
        var dataUrl = fr.result;
        // Paint image, as a proof of concept
        var img = document.createElement('img');
        img.src = dataUrl;
        document.body.appendChild(img);
    };
    fr.readAsDataURL(blob);
};
x.send();

The previous code can be copied to the console, and you will see a small image with the YouTube icon at the bottom of the page. Demo link: http://jsfiddle.net/4Y7VP/

+8

Source: https://habr.com/ru/post/1537998/


All Articles