Saving a Blob Image

I have a function that allows me to transfer the contents, name and type of a file, and the function will automatically save it. It works great for text documents, but now I'm trying to save it in other files, such as an image file. Somewhere along the line, its receipt is damaged and does not work.

function write(text, filename, mime){
    var file = new Blob([text], {type:mime}), a = document.createElement('a');

    // Download in IE
    if(window.navigator.msSaveBlob) window.navigator.msSaveBlob(file, filename);

    // Download in compliant browsers
    else{
        var url = URL.createObjectURL(file);
        a.href = url, a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function(){
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);}, 0);}}

write('Plain text', 'demo.txt', 'text/plain');

write(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAAdCAIAAADkY5E+AAAAD0lEQVR42mNg0AthoDMGAE1BDruZMRqXAAAAAElFTkSuQmCC'), 'demo.png', 'image/png');
+4
source share
2 answers

FileSaver.js is a very powerful js script for saving any type of blob file.

Import it, then use it like this:

saveAs(new Blob([file], {type:mime}),filename);
+2
source

ajax? , XmlHttpRequest.responseType 'arraybuffer' 'blob' ( '', blob).

( arraybuffer) (Fiddle):

var xhr = new XMLHttpRequest();

var url = 'https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg';

xhr.responseType = 'arraybuffer'; //Set the response type to arraybuffer so xhr.response returns ArrayBuffer
xhr.open('GET', url , true);

xhr.onreadystatechange = function () {
    if (xhr.readyState == xhr.DONE) {
        //When request is done
        //xhr.response will be an ArrayBuffer
        var file = new Blob([xhr.response], {type:'image/jpeg'});
        saveAs(file, 'image.jpeg');
    }
};

xhr.send(); //Request is sent

2 ( blob) (Fiddle):

var xhr = new XMLHttpRequest();

var url = 'https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg';

xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);

xhr.onreadystatechange = function () {
    if (xhr.readyState == xhr.DONE) {
        //When request is done
        //xhr.response will be a Blob ready to save
        saveAs(xhr.response, 'image.jpeg');
    }
};

xhr.send(); //Request is sent

FileSaver.js, .

:

XmlHttpRequest Standard

XmlHttpRequest Standard ( responseType)

MDN Docs (XmlHttpRequest)

MDN (ArrayBuffer)

+2

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


All Articles