springMVC实现文件下载
一、文件下载原理
1、设置 response 响应头
2、读取文件 -- InputStream
3、写出文件 -- OutputStream
4、执行操作
5、关闭流 (先开后关)
二、实现代码
@RequestMapping(value="/downloadFile")
public String downloads(HttpServletResponse response) throws Exception{
String path = "C:/";
String fileName = "default.png";
//1、设置response 响应头
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
注: 直接请求url: "/downloadFile",即可实现文件下载。 (需:C盘有一个 default.png 的文件)
三、使用spirng 自带的 ResponseEntity 实现
@RequestMapping(value="/downloadEntity")
public ResponseEntity<byte[]> downloadsEntity(HttpServletRequest request) throws Exception{
String path = "C:/";
String fileName = "default.png";
File file=new File(path,fileName);
if(!file.isFile()){
return null;
}
@SuppressWarnings("resource")
InputStream input=new FileInputStream(file);
byte[] buff=new byte[input.available()]; // 获取文件大小
input.read(buff) ;
HttpHeaders headers=new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="+fileName);
HttpStatus status=HttpStatus.OK;
ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(buff,headers,status);
return entity;
}
四、前端页面
1、html页面直接下载: <a href="/downloads/downloadFile">点击下载</a><br><br>
2、js 代码下载:
a. html:<button id="btn_location">location下载</button><br><br>
b. js :
$("#btn_location").click(function(){
window.location.href="/downloads/downloadFile";
});