小编典典

浏览器/ HTML强制从src =“ data:image / jpeg; base64…”下载图像

javascript

我在客户端生成图像,并使用HTML显示如下:

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgM...."/>

我想提供下载生成的图像的可能性。

我怎么能知道浏览器正在打开文件保存对话框(或者只是将chrome或firefox这样的图像下载到下载文件夹中即可),从而允许用户保存图像
而无需右键单击并另存为 图像?

我希望没有服务器交互的解决方案。因此,我知道如果我先上传图像然后开始下载,那将是可能的。

非常感谢!


阅读 2588

收藏
2020-04-25

共1个答案

小编典典

只需替换image/jpegapplication/octet-stream。客户端不会将该URL识别为可内联资源,并提示下载对话框。

一个简单的JavaScript解决方案是:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element,

另一种方法是使用blob:URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};
2020-04-25