保存图像 Blob

9
我有一个函数,可以传递文件内容、名称和类型,函数会自动保存它。这对于文本文档非常有效,但现在我想要它保存其他文件,比如图像文件。不知何时出现了问题,导致文件被破坏而无法使用。
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');

2
FileSaver.js应该可以解决你的问题。 - Aefits
更新了我的答案,附上可运行的代码和fiddle链接。 - Cheloide
你不能简单地调用 atob 并期望以正确的方式将字节返回到 Blob 中。 - Kaiido
我想出了一个解决方案并将其发布到类似的问题中:https://dev59.com/XW865IYBdhLWcg3wQMSW#72211735 - Nate
2个回答

8

FileSaver.js 是一个非常强大的 JavaScript 脚本,可以保存任何类型的 Blob 文件。

导入它,然后像这样使用:

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

1
谢谢,我没有考虑到 blob 文件大小限制。我能使文本正常工作,但不能工作的是图片:saveAs(new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}), "hello world.txt");var img = atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAAdCAIAAADkY5E+AAAAD0lEQVR42mNg0AthoDMGAE1BDruZMRqXAAAAAElFTkSuQmCC'); saveAs(new Blob([img], {type: "image/png"}), "test.png"); - GFL
编辑后添加了 MIME 类型 - m.nachury

5

你是否正在使用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将Blob保存为文件。

有用的链接:

XmlHttpRequest标准

XmlHttpRequest标准(responseType属性)

MDN文档(XmlHttpRequest)

MDN文档(ArrayBuffer)


赞 responseType 设置 :-) - SkyBlues87

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接