問題描述

我在客戶端生成一個影像,我用 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

  • Typed arrays

  • URL.createObjectURL

  • BlobBlobBuilder

次佳解決方案

您可以使用標籤上的下載屬性…

<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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇