[英]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。 它在瀏覽器中打開文件,然后下載。
我設置了一個二進制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.