方式一
@GetMapping("/download")
public ResponseEntity<byte[]> download1(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取真实路径
//获取 文件存储的路径
String realPath = request.getServletContext().getRealPath("/WEB-INF/imgs/");
//下载的文件的全路径
String allPath = realPath + filename;
FileInputStream inputStream = new FileInputStream(allPath);
//获取流数组
byte[] bytes = new byte[inputStream.available()];
//设置下载的文件名
String newFileName = RandomUtil.getFileName(filename);
//设置头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", URLEncoder.encode(newFileName, "utf-8"));
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
return responseEntity;
}
方式二
@GetMapping("/download2")
public void download2(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取 文件存储的路径
String realPath = request.getServletContext().getRealPath("/WEB-INF/imgs/");
//下载的文件的全路径
String allPath = realPath + filename;
//获取流信息
try(FileInputStream fileInputStream = new FileInputStream(allPath)){
//设置 响应的头信息 分号不能错
response.setHeader("content-disposition","attachment;filename="+RandomUtil.getFileName(filename));
//写给客户端
//把 fileInputStream的流信息 复制给 response的输出流
//只要把流的信息 给 response.getOutputStream() 就会触发浏览器的下载
IOUtils.copy(fileInputStream,response.getOutputStream());
}
}
html
<h3>文件下载</h3>
<ul>
<li>
<%--浏览器 可以打开图片文件的 ,直接显示 没有下载--%>
<a href="/spring_mvc_base/game/download?filename=a1.jpg">图片</a>
</li>
<li>
<a href="/spring_mvc_base/game/download?filename=test1.xlsx">excel</a>
</li>
<li>
<a href="/spring_mvc_base/game/download2?filename=test2.pdf">pdf</a>
</li>
<li>
<a href="/spring_mvc_base/game/download2?filename=test3.rar">压缩包</a>
</li>
<li>
<a href="/spring_mvc_base/game/download2?filename=test4.docx">word</a>
</li>
</ul>
axios下载流方式
downLoadData() {
// 参数
let param = {};
download(param)
.then((res) => {
const a = document.createElement("a");
const blob = new Blob([res], {
type: "application/excel",
});
const objectUrl = URL.createObjectURL(blob);
a.setAttribute("href", objectUrl);
a.setAttribute("download", `表格数据.xls`);
a.click();
})
},
封装的 api
export function download(data) {
return request({
url: "project/download",
method: 'post',
data: data,
responseType: 'arraybuffer',
})
}