浏览器/HTML 强制从 src="data:image/jpeg;base64..." 下载图像 [英] Browser/HTML Force download of image from src="data:image/jpeg;base64..."
问题描述
我正在客户端生成一个图像,并用 HTML 显示它,如下所示:
I am generating a image on client side and I display it with HTML like this:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgM...."/>
我想提供下载生成的图像的可能性.
I want to offer the possibility to download the generated Image.
我怎么能意识到浏览器正在打开一个文件保存对话框(或者只是将像 chrome 或 firefox 这样的图像下载到下载文件夹就可以了),它允许用户保存图像而无需右键单击并保存如图片所示?
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 as on the image?
我更喜欢没有服务器交互的解决方案.所以我知道如果我先上传图像然后开始下载是可能的.
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.
非常感谢!
推荐答案
只需将 image/jpeg
替换为 application/octet-stream
.客户端不会将该 URL 识别为可内嵌的资源,并提示下载对话框.
Simply replace image/jpeg
with application/octet-stream
. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.
一个简单的 JavaScript 解决方案是:
A simple JavaScript solution would be:
//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:
Another method is to use a 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!
};
相关文档
atob
莉>- 类型化数组
URL.createObjectURL
一个>Blob
和BlobBuilder
这篇关于浏览器/HTML 强制从 src="data:image/jpeg;base64..." 下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!