我们正在使用FusionCharts,并且它具有在客户端使用JavaScript导出CSV数据的功能,我们希望能够将该数据获取并在浏览器中实时创建文件。这是否可能?如何实现?
尝试以下代码,可以让您访问客户端文件系统,但只适用于IE浏览器。
<html>
<body>
<script language="JScript"></script>
Get the size for the file "test.txt"
<form name="myForm">
<input type="Button" value="Get Size" onClick='getsize()'>
</form>
</body>
</html>
由于马克的答案(愚蠢地)被转换为评论,而其他答案实际上没有回答问题,所以这里是答案:
<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>
// 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);
}
<%@ 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>
这段代码已经在生产环境中测试并部署/运行,同时也具备跨浏览器的功能。
根据设计,JavaScript 无法直接访问本地磁盘。
我认为你可以将所有数据从 JavaScript 传递到服务器端代码(PHP、ASP.NET、Java 等),然后以某种方式将其流式传输到浏览器。