問題描述
我在客户端生成一個圖像,我用 HTML 顯示它:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgM...."/>
我想提供下載生成的圖像的可能性。
我如何才能意識到瀏覽器正在打開一個文件保存 dialoge(或者只需下載像 chrome 或 firefox 這樣的圖像到下載文件夾),這樣可以讓用户保存圖像而不用右鍵點擊並保存在圖像上?
我更喜歡沒有服務器交互的解決方案。所以我知道如果我第一次上傳圖像然後開始下載是可能的。
非常感謝!
最佳解決方案
只需用 application/octet-stream 代替 image/jpeg 。客户端不會將 URL 識別為 inline-able 資源,並提示下載對話框。
一個簡單的 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!
};
相關文件
-
atob -
URL.createObjectURL -
Blob和BlobBuilder
次佳解決方案
您可以使用標籤上的下載屬性…
<a href="" download="filename.jpg"></a>
查看更多:https://developer.mozilla.org/en/HTML/element/a#attr-download
第三種解決方案
我想一個 img 標籤需要作為一個標籤的孩子,如下所示:
<a download="YourFileName.jpeg" href="">
<img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>
要麼
<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
<img src="/path/to/OtherFile.jpg"></img>
</a>
只有使用#15 中所述的標籤才能使用最新版本的 Firefox 和 Chrome,但是將同樣的圖像數據放在 a.href 和 img.src 標籤中對我有用。
從 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);
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。