SpringMvc文件下载
1.方式一:基于ResponseEntity实现
@RequestMapping("/testHttpMessageDown")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
// 需要下载的文件
File file = new File("E://123.jpg");
byte[] body = null;
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
2.方式二:通用下载实现
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws IOException{
File file = new File("d://owned.xls");
//设置响应头和客户端保存文件名
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
try {
//打开本地文件流
InputStream inputStream = new FileInputStream(file);
//激活下载操作
OutputStream os = response.getOutputStream();
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (Exception e){
throw e;
}
}
版权声明:本文为Pan_BY原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。