簡體   English   中英

無法下載具有下載屬性的文本文件

[英]Unable to download text file with download attribute

我正在嘗試使用以下代碼片段下載文件。 文件是文本文件。

var element = document.createElement('a');
element.setAttribute('href', URL);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);

我正在測試Chrome。 它在瀏覽器中打開文件,然后下載。

參見MDN

此屬性僅適用於同源URL。

可能是您鏈接到了其他來源的URL。

您不能使用download屬性覆蓋它。

而是設置一個Content-Disposition HTTP響應標頭。

我設置了一個二進制mime類型,因為瀏覽器可以識別text/plain ,而只是打開text/plain而不顯示下載窗口。 試試這個代碼

 var text = "Test Line1\\n Line2 \\n Line3"; var fileBlob = new Blob([text], {type: "application/octet-binary"}); var link = document.createElement("a"); link.setAttribute("href", URL.createObjectURL(fileBlob)); link.setAttribute("download", "HelloWorld.txt"); link.appendChild(document.createTextNode("Click here to download file")); document.body.appendChild(link); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM