最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Saving an Image Blob - Stack Overflow

programmeradmin3浏览0评论

I have a function that allows me to pass file content, name, and type and the function will automatically save it. It works great for text based documents, but now I'm trying to have it save other files, like an image file. Somewhere along the line its getting corrupted and isn't working.

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');

I have a function that allows me to pass file content, name, and type and the function will automatically save it. It works great for text based documents, but now I'm trying to have it save other files, like an image file. Somewhere along the line its getting corrupted and isn't working.

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');
Share Improve this question asked Jul 21, 2017 at 13:38 GFLGFL 1,4243 gold badges17 silver badges29 bronze badges 5
  • 2 FileSaver.js should solve your problem. – Aefits Commented Jul 21, 2017 at 14:34
  • Updated my answer with working code and fiddle. – Cheloide Commented Jul 21, 2017 at 16:10
  • Possible duplicate of Convert Data URI to File then append to FormData – Kaiido Commented Jul 21, 2017 at 17:07
  • You can't simply call atob and hope for the bytes to come back in the Blob correctly. – Kaiido Commented Jul 21, 2017 at 17:07
  • I came up with a solution and posted it to a similar question: stackoverflow.com/a/72211735/4946681 – Nate Commented May 13, 2022 at 15:26
Add a comment  | 

2 Answers 2

Reset to default 8

FileSaver.js a very powerful js script to save any type of blob file.

Import it then use it like this:

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

Are you fetching the file using ajax? if so, you should set XmlHttpRequest.responseType to 'arraybuffer' or 'blob' (default is '' and that will not work with binaries or blob data).

Working example (using 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

Working example 2 (using 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

I recommend FileSaver.js to save the blobs as files.

Useful links:

XmlHttpRequest Standard

XmlHttpRequest Standard (responseType attribute)

MDN Docs (XmlHttpRequest)

MDN Docs (ArrayBuffer)

发布评论

评论列表(0)

  1. 暂无评论