Javascript 浏览器/HTML 强制从 src="data:image/jpeg;base64..." 下载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10473932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:29:50  来源:igfitidea点击:

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

javascriptimagehtmlbrowser

提问by alex

I am generating a image on client side and I display it with HTML like this:

我在客户端生成一个图像,并用 HTML 显示它,如下所示:

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

I want to offer the possibility to download the generated Image.

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

How can I realize that the browser is opening a file save dialoge (or just download the image like chrome or firefox to the download folder would do) which allows the user to save the image without doing right click and save ason the image?

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

I would prefer a solution without server interaction. So I am aware that it would be possible if I first upload the Image and then start the download.

我更喜欢没有服务器交互的解决方案。所以我知道如果我先上传图像然后开始下载是可能的。

Thanks a lot!

非常感谢!

回答by Rob W

Simply replace image/jpegwith application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

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

A simple JavaScript solution would be:

一个简单的 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, 

Another method is to use a blob:URI:

另一种方法是使用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!
};

Relevant documentation

相关文件

回答by Bruce Aldridge

you can use the download attribute on an a tag ...

您可以在 a 标签上使用下载属性...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

查看更多:https: //developer.mozilla.org/en/HTML/element/a#attr-download

回答by user3521208

I guess an imgtag is needed as a child of an atag, the following way:

我猜的IMG标签需要作为一个孩子一个标签,方式如下:

<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
    <img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>

or

或者

<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
    <img src="/path/to/OtherFile.jpg"></img>
</a>

Only using the atag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.hrefand img.srctags worked for me.

在最新版本的 Firefox 和 Chrome 中,仅使用#15 中解释的a标签对我不起作用,但将相同的图像数据放在a.hrefimg.src标签中对我有用

From JavaScript it could be generated like this:

从 JavaScript 可以这样生成:

var data = canvas.toDataURL("image/jpeg");

var img = document.createElement('img');
img.src = data;

var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);

var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);

回答by jesal

Take a look at FileSaver.js. It provides a handy saveAsfunction which takes care of most browser specific quirks.

看看FileSaver.js。它提供了一个方便的saveAs功能,可以处理大多数浏览器特定的怪癖。