实际需求:在许多开发当中,点击下载(尤其PDF、图像格式)的文件,会直接在浏览器打开,不会直接的下载;所以此代码就是处理防止浏览器直接打开,点击下载接口直接下载到本地。
1.后端-代码块
@GetMapping(value = "/pdfDownload")
@ApiOperation(value = "直接下载")
public void download(@RequestParam(value = "commendId") String commendId,
HttpServletResponse response) throws IOException {
ModelCommendFile cf = commendFileService.findById(commendId);
//文件(绝对路径)
String fielUrl = cf.getCommendFileUrl();
File file = new File(commendFile.split("/")[0] + fielUrl);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; fileName=" + file.getName());
OutputStream out = response.getOutputStream();
byte[] bytes = Files.toByteArray(file);
out.write(bytes);
out.close();
}
2.后端返回数据
3.前端-代码块
<a href="http://127.0.0.1:8080/apis/file/pdfDownload?commendId=123(参数)" rel="nofollow">下载文件</a>