Springboot下载⽂件的2种⽅式Spring boot中下载⽂件的2种⽅式
1. 通过HttpServletResponse的OutputStream实现
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
log.info("进⼊下载⽅法。。。。");
String fileName = "CentOS-7-x86_64-Minimal-1810.iso";// 设置⽂件名,根据业务需要替换成要下载的⽂件名
if (fileName != null) {
//设置⽂件路径
String realPath = "D:\\tmp\\";
File file = new File(realPath , fileName);
if (ists()) {
response.setContentType("application/octet-stream");//
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置⽂件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = OutputStream();
int i = ad(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = ad(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
spring framework需要下载吗return null;
}
2. 通过ResponseEntity<InputStreamResource>实现
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFile(String fileName)
throws IOException {
log.info("进⼊下载⽅法...");
//读取⽂件
String filePath = "D:/tmp/" + fileName + ".iso";
FileSystemResource file = new FileSystemResource(filePath);
//设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", Filename()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.
tLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStream()));
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论