仅使用 Javascript(无服务器端)将文本区域内容下载为文件

新手上路,请多包涵

我被要求制作一个“下载”按钮,将文本区域的内容下载到与文件相同的页面上,并显示浏览器的“另存为…”对话框。复制/粘贴可以很好地完成这项工作,但这是一项“要求”。

现在,我只是将 textarea 的内容发布到服务器,服务器用 Content-disposition: attachment 回应它们。有没有办法只用客户端 Javascript 来做到这一点?

原文由 Thilo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 261
1 个回答

这可能是您正在寻找的内容: http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

它使用浏览器的下载对话,但只支持 FF 和 Chrome,现在可能还有更多浏览器?


    function saveTextAsFile(textToWrite, fileNameToSaveAs)
    {
    	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    	var downloadLink = document.createElement("a");
    	downloadLink.download = fileNameToSaveAs;
    	downloadLink.innerHTML = "Download File";
    	if (window.webkitURL != null)
    	{
    		// Chrome allows the link to be clicked
    		// without actually adding it to the DOM.
    		downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    	}
    	else
    	{
    		// Firefox requires the link to be added to the DOM
    		// before it can be clicked.
    		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    		downloadLink.onclick = destroyClickedElement;
    		downloadLink.style.display = "none";
    		document.body.appendChild(downloadLink);
    	}

    	downloadLink.click();
    }
 <textarea id=t>Hey</textarea><br>
<button onclick=saveTextAsFile(t.value,'download.txt')>Download</button>

原文由 NatureShade 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题