仅使用 Javascript(无服务器端)将 textarea 内容下载为文件 [英] Download textarea contents as a file using only Javascript (no server-side)
问题描述
我被要求制作一个下载"按钮,用于下载与文件位于同一页面上的文本区域的内容,并显示浏览器的另存为..."对话框.复制/粘贴可以很好地完成这项工作,但这是一个要求".
I am being asked to make a "download" button that downloads the contents of a textarea on the same page as a file, with the browser's "Save As..." dialog showing up. Copy/paste would do the job just fine, but it is a "requirement".
现在,我只是将 textarea 的内容发布到服务器,服务器用 Content-disposition:attachment
回应它们.有没有办法只用客户端 Javascript 来做到这一点?
Right now, I am just posting the contents of the textarea to the server, which echos them back with Content-disposition: attachment
slapped on. Is there a way to do this with just client-side Javascript?
推荐答案
它使用浏览器的下载对话框,但只支持FF和Chrome,现在可能有更多浏览器?
It uses the browser's download dialogue, but supports only FF and Chrome, and maybe more browsers now?
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>
这篇关于仅使用 Javascript(无服务器端)将 textarea 内容下载为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!