springboot 实现 下载
时间: 2024-01-10 11:03:05 浏览: 18
文件的功能该如何实现?
可以通过在Controller中添加一个接口,使用HttpServletResponse的输出流将文件写入响应体中,然后设置响应头让浏览器进行下载。具体代码如下:
@GetMapping("/download")
public void download(HttpServletResponse response) {
File file = new File("file_path");
if(file.exists()) {
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
byte[] buff = new byte[1024];
int byteRead;
while (-1 != (byteRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, byteRead);
}
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}