1.ResponseEntity方式文件下载
注:此方式基于SpringMVC
@GetMapping("/responseEntityDownload")
public ResponseEntity downFile(){
File file = new File("E:\文件上传测试", "mmexport1600165842010.jpg");
byte[] bytes = new byte[0];
try (
// 高效文件读取流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
) {
bytes = new byte[bis.available()];
bis.read(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//将要下载文件内容返回
HttpHeaders httpHeaders = new HttpHeaders();
// httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(file.getName(),"UTF-8"));
// 两种设置方式都可。
// httpHeaders.set("Content-Disposition","attachment;filename="+ file.getName() +"");
httpHeaders.set("Content-Disposition","attachment;filename="+ file.getName() +"");
ResponseEntity requestEntity = new ResponseEntity(bytes,httpHeaders, HttpStatus.OK);
return requestEntity;
}
2.response下载
@GetMapping("/responseWhileDownload")
public void responseWhileDownload(HttpServletResponse response) throws IOException {
File file = new File("E:\文件上传测试", "WPS_Setup_11830.exe");
byte[] bytes = null;
// response重置
response.reset();
// 设置编码
response.setCharacterEncoding("UTF-8");
// 设置流
response.setContentType("application/octet-stream");
// 设置header
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"UTF-8") +"");
// 设置header告知大小
response.addHeader("Content-Length", "" + file.length());
ServletOutputStream outputStream = response.getOutputStream();
try (
// 高效文件读取流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
// response输出流
BufferedOutputStream bos = new BufferedOutputStream(outputStream)
) {
bytes = new byte[8192];
int length = 0;
// 读取完毕后会返回-1,故结束循环
while ((length = bis.read(bytes)) != -1){
bos.write(bytes, 0, length);
}
bis.close();
// 输出流切记要关闭不然无法完成下载
bos.close();
// response的输出流也必须关闭不然后台全是报错
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
前端代码
ResponseEntity方式文件下载response方式文件下载



