相比之前的下载,这中下载更加普遍,原因如下
1.byte[] body = FileUtils.readFileToByteArray(file);,当文件下载过大时候,占用内存过多
所以选择如下下载,代码如下
1.JS文件
//这种方法不能使用get提交,必须使用post提交
$(".testDownLoad").click(function(){
$.post($(this).attr("href"));
});
2.jsp文件
<a class="testDownLoad" href="springMVC/testDownLoadTwo?fileName=setup_11.4.0.2001s.exe">文件下载2</a></br>
3.后台代码
@RequestMapping("/testDownLoadTwo")
public void testDownLoadTwo(@RequestParam("fileName") String fileName,HttpServletResponse response) throws IOException{
//传进来的是ISO-8859-1,转化成默认字符集
String fileNames = new String(fileName.getBytes("ISO-8859-1"),"utf-8");
//1.找到要下载的文件
File file = new File("G:/"+fileNames);
Long length = file.length();
//2.设置返回头
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition","attachment;filename="+fileName);//这里必须使用传经来的fileName
response.setHeader("Content-Length",length+"");
//3.返回数据
FileInputStream in = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] suffer = new byte[1024];
while(in.read(suffer)!=-1){
out.write(suffer);
}
out.close();
in.close();
}