浏览器下载文件

浏览器下载文件

solution:读取文件,设置响应头,写入返回的流
前端用http请求而不能用ajax请求(JQuery的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。) (前端用a标签自动点击)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Controller
@RequestMapping("/view")
public class ViewController {

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getTemplate(HttpServletRequest request,HttpServletResponse response)throws IOException {
//服务器下的相对路径
String path = "WEB-INF/document/template.csv";
//通过相对路径获取真实路径
File csvFile = new File(request.getServletContext().getRealPath(path));
try{
ServletOutputStream out = response.getOutputStream();
FileInputStream csvInputStream = new FileInputStream(csvFile);
BufferedOutputStream outputStream = new BufferedOutputStream(out);
//让服务器告诉浏览器它发送的数据属于什么文件类型
response.setContentType("multipart/form-data");
//inline 和 attachment:将文件内容直接显示在页面 attachment:弹出对话框让用户下载
response.setHeader("Content-Disposition", "attachment;fileName="+"test.csv");
response.addHeader("Content-Length", String.valueOf(csvFile.length()));
//设置缓冲区大小
byte []buffer = new byte[1024];
int ch = 0;
while ((ch = csvInputStream.read(buffer)) != -1){
outputStream.write(buffer,0,ch);
}
outputStream.flush();
out.close();
outputStream.close();
csvInputStream.close();

} catch(Exception e){
e.printStackTrace();
}finally {
}
}
}
Thanks!