SpringBoot实现文件下载

下面是用SpringBoot完成文件下载的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Controller
@RequestMapping("/download")
public class DownloadController {

@ResponseBody
@RequestMapping("/download")
public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
String downloadFilePath="D:\\laiscdata";
File file = new File(downloadFilePath +'\\'+ fileName);
if(!file.exists()){
return "下载文件不存在";
}
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
System.out.println("程序错误:"+e);
return "下载失败";
}
return "下载成功";
}
}

测试:访问http://localhost:8088/download/download?fileName=1.zip