[英]File download via JavaScript?
So I had a thought today. 所以今天我想到了。 I generate CSV from data already in memory in my JavaScript application, then pump that data to the user's browser via a File download prompt -- all in JavaScript --.
我从我的JavaScript应用程序中已经存储在内存中的数据生成CSV,然后通过文件下载提示将这些数据泵送到用户的浏览器 - 所有这些都在JavaScript中。
Is this possible? 这可能吗?
If you want to do it entirely on the client-side, without any server interaction, you will need at least the help of Flash. 如果你想完全在客户端完成,没有任何服务器交互,你至少需要Flash的帮助。
Give a look to Downloadify , is the best I've seen for client-side file generation. 看看Downloadify ,是我见过的最好的客户端文件生成。
The solution to download local/client-side contents via javascript is not straight forward. 通过javascript下载本地/客户端内容的解决方案并不简单。 I have implemented one solution using smartclient-html-jsp.
我使用smartclient-html-jsp实现了一个解决方案。
Here is the solution: 这是解决方案:
// code start //代码开始
<%@ 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>
</BODY>
</HTML>
// code end //代码结束
This code is tested and deployed/working in production environment, also this is cross-browser functionality. 此代码在生产环境中经过测试和部署/工作,这也是跨浏览器功能。
Thanks Shailendra 谢谢Shailendra
If your server is setup to trigger a download for your given MIME type then you can simply do a straight location.href = 'myFile.csv'
. 如果您的服务器设置为触发给定MIME类型的下载,那么您只需执行直接
location.href = 'myFile.csv'
。
This will prompt the user to open or save the file as you'd like. 这将提示用户根据需要打开或保存文件。
This does require that your server be configured to behave this way. 这确实要求您的服务器配置为以这种方式运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.