一、方法一
1.1 Java代码
@RequestMapping(value="/downloadFile")
public String downloads(HttpServletResponse response) throws Exception{
String path = "D:\\tmp/";
String fileName = "fillp_server.txt";
//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;
}
1.2 前端代码
<a href="/downloadFile">click download</a>
二、方法二:使用spirng 自带的 ResponseEntity 实现
2.1 Java代码
@RequestMapping(value="/downloadEntity")
@SuppressWarnings("resource")
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;
}
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<>(buff,headers,status);
return entity;
}
2.2 前端代码
<a href="/downloadEntity">click download</a>