用jquery ajax实现 文件下载功能。是不是要使用插件才行啊。
我用超链接做下载的可以,用ajax触发就不行,弹不出下载的对话框啊。用alert(回传的数据),可以看到要下载的文件的内容都写到里面去了,怎么回事啊。
后台代码:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/");
System.out.println(ctxPath);
String downLoadPath = "c:/checkoute8cdata/test220.csv";
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="
+ new String("test".getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
}
前台代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Panel</title>
<script type="text/javascript" src="scripts/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
document.getElementById("panel").onclick=function(){
$.ajax({
type: "get",
url: "DownloadServlet"
});
}
})
</script>
</head>
<body>
<div id="panel">download</div>
<%--<a href="DownloadServlet">download</a>
--%></body>
</html>
[解决办法]
数据返回了,你怎么处理的。
[解决办法]
既然用jquery 为什么要document.getElementById("panel").onclick=
改成 $("#panel").click(function(){});
firebug 测试下..
[解决办法]
post 呢