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

发布于 2024-07-14 07:40:29 字数 209 浏览 6 评论 0原文

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

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

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".

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

撧情箌佬 2024-07-21 07:40:29

这可能就是您正在寻找的:
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>

This may be what you are looking for:
http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

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>

一刻暧昧 2024-07-21 07:40:29

我在这里找到了一个简单的解决方案: https://codepen.io

My text area:<br />
<textarea rows='10' cols='80' id='myTextArea' ></textarea>

<br /><br />

Download button: <br />
<input value='download' type='button'
onclick='doDL(document.getElementById("myTextArea").value)' />


<script type='text/javascript'>
function doDL(s){
    function dataUrl(data) {return "data:x-application/text," + escape(data);}
    window.open(dataUrl(s));
}
</script>

希望它会有所帮助。

I found a simple solution here: https://codepen.io

My text area:<br />
<textarea rows='10' cols='80' id='myTextArea' ></textarea>

<br /><br />

Download button: <br />
<input value='download' type='button'
onclick='doDL(document.getElementById("myTextArea").value)' />


<script type='text/javascript'>
function doDL(s){
    function dataUrl(data) {return "data:x-application/text," + escape(data);}
    window.open(dataUrl(s));
}
</script>

Hope it will help.

巴黎夜雨 2024-07-21 07:40:29

您可以尝试 window.location = "data:application/octet-stream,"+text 但这没有提供建议名称的机制,而且 IE 的上限非常小关于数据 URI 的最大长度,这可能是一个问题。

You could try window.location = "data:application/octet-stream,"+text but that doesn't provide a mechanism through which you can suggest a name, and also IE has a very small cap on the maximum length of a data URI which could be a problem.

岁月流歌 2024-07-21 07:40:29

有一些 javascript 库可以通过小型嵌入式 SWF 文件执行此类操作。 例如这个

There were some javascript libraries that did this kind of thing, via small embedded SWF file. For example this one.

勿忘心安 2024-07-21 07:40:29

您可以使用 data: URI为其指定文件名,同时仍然下载文本。 尝试这个:

document.getElementById("download").onclick = function(){
  var l = document.createElement("a");
  l.href = "data:text/plain;charset=UTF-8," + document.getElementById("dload-txt").value;
  l.setAttribute("download", document.getElementById("dload-fn").value);
  l.click();
}
textarea { width: 200px; height: 75px }
input { width: 200px }
<textarea placeholder="Enter text to download" id="dload-txt"></textarea><br/>
<input placeholder="Enter file name to download as" id="dload-fn"/><br/><br/>
<button id="download">Download</button>

这适用于大多数浏览器。

它的作用是从文本区域和输入中获取必要的数据,创建一个包含 hrefdata:text/plain;UTF-8,

这里唯一不与所有浏览器兼容的东西是:

  1. data: 用于将数据存储为链接的 URI。 数据:CanIUse 上的 URI

  2. click() 函数来单击链接。 CanIUse 上的 HTMLElement.click()

  3. download 属性表示下载。 CanIUse 上的下载属性

所以基本上:

  • 在 IE 中不起作用

  • 不适用于 Opera Mini

  • 不适用于早期版本的 Firefox、Chrome、Safari、Opera 和 iOS Safari

否则,这适用于所有主要浏览器,并且不需要任何 Blob 对象。

CanIUse 上的 Blob 构建

CanIUse 上的 Blob URL

You can use data: URIs and give it a file name, while still downloading the text. Try this:

document.getElementById("download").onclick = function(){
  var l = document.createElement("a");
  l.href = "data:text/plain;charset=UTF-8," + document.getElementById("dload-txt").value;
  l.setAttribute("download", document.getElementById("dload-fn").value);
  l.click();
}
textarea { width: 200px; height: 75px }
input { width: 200px }
<textarea placeholder="Enter text to download" id="dload-txt"></textarea><br/>
<input placeholder="Enter file name to download as" id="dload-fn"/><br/><br/>
<button id="download">Download</button>

This works in most browsers.

What it does is get the necessary data from the textarea and input, create a link that has an href to data:text/plain;UTF-8,<textarea data>, and set the download attribute with the name set by the <input> element. Then click the link, which will download the text.

The only not-all-browser-compatible things here are:

  1. data: URIs for storing the data as a link. data: URIs on CanIUse

  2. click() function to click the link. HTMLElement.click() on CanIUse

  3. download attribute to signify a download. download attribute on CanIUse

So basically:

  • Does not work in IE

  • Does not work in Opera Mini

  • Does not work in very early versions of Firefox, Chrome, Safari, Opera, and iOS Safari

Otherwise, this works in all major browsers, and doesn't need any Blob object.

Blob construction on CanIUse

Blob URLs on CanIUse

小矜持 2024-07-21 07:40:29

绝对可以使用 HTML5 saveAs 函数的跨浏览器 JavaScript 实现:https:// github.com/koffsyrup/FileSaver.js

如果您只想保存文本,那么上述脚本适用于所有浏览器(包括所有版本的 IE),不需要 SWF。

Absolutely possible using this cross browser JavaScript implementation of the HTML5 saveAs function: https://github.com/koffsyrup/FileSaver.js

If all you want to do is save text then the above script works in all browsers(including all versions of IE), no SWF required.

瑾夏年华 2024-07-21 07:40:29

根据@Cyrlop的答案和 https://stackoverflow.com/a/41948732/3096687,这提供了一种指定的方法文件名:

            function doDownload(str) {
              function dataUrl(data) {
                return "data:x-application/xml;charset=utf-8," + escape(data);
              }
              var downloadLink = document.createElement("a");
              downloadLink.href = dataUrl(str);
              downloadLink.download = "foo.xml";

              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);
            }

如果您不介意在 JavaScript 中包含更多字节,@Superphonic 的解决方案可能会更好。

Based on @Cyrlop's answer and https://stackoverflow.com/a/41948732/3096687, this gives a way to specify a filename:

            function doDownload(str) {
              function dataUrl(data) {
                return "data:x-application/xml;charset=utf-8," + escape(data);
              }
              var downloadLink = document.createElement("a");
              downloadLink.href = dataUrl(str);
              downloadLink.download = "foo.xml";

              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);
            }

@Superphonic's solution is likely nicer if you don't mind including more bytes in your JavaScript.

溺渁∝ 2024-07-21 07:40:29

通过创建一个框架,在其中写入内容,然后调用
IE 中的 document.execCommand('saveas', ...) 以及 Mozilla 中的 nsIFilePicker,但我相信这需要一些非凡的权限(例如成为浏览器本身的一部分)。

It might be possible by creating a frame, writing contents there, then calling
document.execCommand('saveas', ...) in IE and something with nsIFilePicker in Mozilla, but I believe that would require some extraordinary privileges (like being part of the browser itself).

戴着白色围巾的女孩 2024-07-21 07:40:29

简短的回答:这是不可能的。
您必须将其 POST 到服务器,服务器的响应可以是“Content-disposition:附件”。

Short answer: it's not posible.
You have to POST it to server, and response from server can be "Content-disposition: attachment".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文