下面兩種寫法都能達到「點擊後把圖片存到本機」的效果,核心都是開一個隱形視窗載入目標資源,再呼叫 execCommand("SaveAs")。
<script>
function SaveAs5(imgURL)
{
var oPop = window.open(imgURL, "", "width=1, height=1, top=5000, left=5000");
for(; oPop.document.readyState != "complete"; )
{
if (oPop.document.readyState == "complete") break;
}
oPop.document.execCommand("SaveAs");
oPop.close();
}
</script>
<img src="t_screenshot_17616.jpg" id="DemoImg" border="0" onclick="SaveAs5(this.src)">
<script>
function SaveAs5(imgURL)
{
var oPop = window.open(imgURL, "", "width=1, height=1, top=5000, left=5000");
for(; oPop.document.readyState != "complete"; )
{
if (oPop.document.readyState == "complete") break;
}
oPop.document.execCommand("SaveAs");
oPop.close();
}
</script>
<img src="../t_screenshot_17616.jpg" id="DemoImg" border="0">
<a href="#" onclick="SaveAs5(document.getElementById('DemoImg').src)">點擊這裡下載圖片</a>
關鍵在 window.open 的第三個參數:把視窗尺寸設為 1×1,並定位到 top=5000, left=5000,讓它落在視線之外。等 document.readyState 變為 complete 後呼叫 execCommand("SaveAs"),瀏覽器就會跳出下載對話框,最後關閉這個隱形視窗。
那段 for 迴圈是忙等待(busy wait),會佔用主執行緒,實作上不理想;更恰當的做法是用 onload 回呼。
更重要的是:這套方案只適用於 IE。document.execCommand 已被標示為 deprecated,非 IE 瀏覽器不支援,且以隱形視窗觸發下載的行為在現代瀏覽器中會被阻擋。
若要在今天的瀏覽器上實作同樣功能,請改用以下方式:
// 下載同源圖片
var a = document.createElement('a');
a.href = imgURL;
a.download = 'filename.jpg';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
若圖片來自跨來源網域,需先透過 fetch 取回 Blob 再建立 objectURL;若需要自訂檔名或後端串流輸出,則由伺服器端設定 Content-Disposition: attachment 標頭是最穩妥的方案。