SpringBoot示例,第2期:文件下载_springboot下载word文件
利用ResponseEntity
利用SpringBoot的ResponseEntity
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws MalformedURLException {
// 文件存储路径,这里需要根据实际情况修改
String filePath = "E:\\xxxx\\upload\\";
Path path = Paths.get(filePath).resolve(fileName).normalize();
Resource resource = new UrlResource(path.toUri());
if (resource.exists() || resource.isReadable()) {
String contentType = null;
try {
contentType = Files.probeContentType(path);
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
利用Response持续输出
输入流中的数据循环写入到响应输出流中,而不是一次性读取到内存,通过响应输出流输出到前端
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) {
String fileName = "example.txt";
String filePath = "E:\\xxx\\upload\\";
File file = new File(filePath + fileName);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
try (FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
// Handle exceptions
}
}
利用Response一次性响应
输入流中的数据一次性读取到内存,通过响应输出流输出到前端
@GetMapping("/download2/{fileName:.+}")
public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
String filePath = "E:\\xxx\\upload\\";
FileInputStream fileInputStream = new FileInputStream(filePath+fileName);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
OutputStream outputStream = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("Content-Type", "application/octet-stream");
response.setContentType("application/octet-stream; charset=UTF-8");
outputStream = response.getOutputStream();
outputStream.write(buffer);
outputStream.flush();
} catch (Exception e) {
// ignored
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
相关文章
- MyBatis如何实现分页查询?_mybatis collection分页查询
- 通过Mybatis Plus实现代码生成器,常见接口实现讲解
- MyBatis-Plus 日常使用指南_mybatis-plus用法
- 聊聊:Mybatis-Plus 新增获取自增列id,这一次帮你总结好
- MyBatis-Plus码之重器 lambda 表达式使用指南,开发效率瞬间提升80%
- Spring Boot整合MybatisPlus和Druid
- mybatis 代码生成插件free-idea-mybatis、mybatisX
- mybatis-plus 团队新作 mybatis-mate 轻松搞定企业级数据处理
- Maven 依赖范围(scope) 和 可选依赖(optional)
- Trace Sql:打通全链路日志最后一里路