javascript 客户端文件创建和下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5107956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Client side file creation and download
提问by arinte
We are using fusioncharts and it has the ability using javascript on the client side to export csv data, we want to be able to take that data and create a file on the fly in the browser. is that possible? How?
我们正在使用 fusioncharts,它能够在客户端使用 javascript 导出 csv 数据,我们希望能够获取该数据并在浏览器中即时创建文件。那可能吗?如何?
采纳答案by Davide Piras
you have no way to touch the local disk with Javascript by design.
您无法通过设计使用 Javascript 访问本地磁盘。
I think you could pass the whole bunch of data from javascript to the server side code ( php, asp.net, java... ) then you could stream it down to the browser somehow.
我认为您可以将所有数据从 javascript 传递到服务器端代码(php、asp.net、java...),然后您可以以某种方式将其流式传输到浏览器。
回答by Matt Sanders
Take a look at filesaver.js. As long as you are okay with IE10+ this is a pretty solid solution that elegantly handles using the best method depending on the browser.
看看filesaver.js。只要您对 IE10+ 没问题,这是一个非常可靠的解决方案,可以根据浏览器使用最佳方法优雅地处理。
回答by B T
Since Marc's answer was (stupidly) converted to a comment, and none of the other answers actually answer the question, here's the answer:
由于 Marc 的回答被(愚蠢地)转换为评论,并且其他答案都没有真正回答这个问题,因此答案如下:
<a id="a">Click me to DL something</a>
<script>
setupDownloadLink(document.getElementById("a"), "moose.txt", "ok")
function setupDownloadLink(element, filename, text) {
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text))
element.setAttribute('download', filename)
}
</script>
This was derived from the answer Marc referenced, which is useful in situations where you're not specifically clicking on a link tag: https://stackoverflow.com/a/3665147/279255
这源自 Marc 引用的答案,这在您没有专门点击链接标签的情况下很有用:https: //stackoverflow.com/a/3665147/279255
// must be called in a click handler or some other user action
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
回答by Pranay Rana
Try below code allow you to access client side file system but this works only in IE browser
尝试以下代码允许您访问客户端文件系统,但这仅适用于 IE 浏览器
<html>
<body>
<script language="JScript">
<!--
function getsize()
{
var myObject, afile, size;
myObject = new ActiveXObject("Scripting.FileSystemObject");
afile = myObject.GetFile("c:\test.txt")
size = afile.Size;
alert("The size of the test.txt file is:" + size);
}
-->
</script>
Get the size for the file "test.txt"
<form name="myForm">
<input type="Button" value="Get Size" onClick='getsize()'>
</form>
</body>
</html>
回答by shaILU
I would suggest you not to create a file locally on client side, instead prompt user (Save As dialog box) to download data generated client side on the location he desires.
我建议您不要在客户端本地创建文件,而是提示用户(另存为对话框)在他想要的位置下载客户端生成的数据。
The solution to download local/client-side contents via javascript is not straight forward. I have implemented one solution using smartclient-html-jsp.
通过 javascript 下载本地/客户端内容的解决方案并不简单。我已经使用 smartclient-html-jsp 实现了一种解决方案。
Here is the solution:
这是解决方案:
- I am in the project build on SmartClient. We need to download/export data of a grid (table like structure).
- We were using RESTish web services to serve the data from Server side. So I could not hit the url two times; one for grid and second time for export/transform the data to download.
- What I did is made two JSPs namely: blank.jsp and export.jsp.
- blank.jsp is literally blank, now I need to export the grid data that I already have on client side.
- Now when ever user asks to export the grid data, I do below:
- Open a new window with url blank.jsp
- using document.write I create a form in it with one field name text in it and set data to export inside it.
- Now POST that form to export.jsp of same heirarchy.
- Contents of export.jsp I am pasting below are self explanatory.
- 我在 SmartClient 上的项目中。我们需要下载/导出网格的数据(类似表格的结构)。
- 我们使用 RESTish Web 服务从服务器端提供数据。所以我无法两次点击网址;一次用于网格,第二次用于导出/转换要下载的数据。
- 我所做的是制作了两个 JSP,即:blank.jsp 和 export.jsp。
- blank.jsp 实际上是空白的,现在我需要导出我已经在客户端拥有的网格数据。
- 现在,当用户要求导出网格数据时,我会执行以下操作:
- 使用 url blank.jsp 打开一个新窗口
- 使用 document.write 我在其中创建了一个表单,其中包含一个字段名称文本,并将数据设置为在其中导出。
- 现在将该表单POST 到相同层次结构的export.jsp。
- 我在下面粘贴的 export.jsp 的内容是不言自明的。
<%@ page import="java.util.*,java.io.*,java.util.Enumeration"%>
<%
response.setContentType ("text/csv");
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment;filename=\"data.csv\"");
String contents = request.getParameter ("text");
if (!(contents!= null && contents!=""))
contents = "No data";
else
contents = contents.replaceAll ("NEW_LINE", "\n");
//Open an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c
InputStream in = new ByteArrayInputStream(contents.getBytes ());
ServletOutputStream outs = response.getOutputStream();
int bit = 256;
int i = 0;
try {
while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
}
//System.out.println("" +bit);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
%>
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
try {window.close ();} catch (e) {alert (e);}
</script>
</BODY>
</HTML>
This code is tested and deployed/working in production environment, also this is cross-browser functionality.
此代码已在生产环境中测试和部署/工作,这也是跨浏览器功能。

