仅使用 Javascript(无服务器端)将 textarea 内容下载为文件 [英] Download textarea contents as a file using only Javascript (no server-side)

查看:32
本文介绍了仅使用 Javascript(无服务器端)将 textarea 内容下载为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

这可能就是您要找的:http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and- Saving-a-text-file-in-html5-using-javascrip/

它使用浏览器的下载对话框,但只支持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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆