前端代码:
<a :href="'/api/down-api/down'" download="down.xlsx">下载</a>
后端代码:
接口:
@ApiOperation(value = "下载") @GetMapping("/down") public void downTemplate(HttpServletResponse response) { String fileName = "down.xlsx"; couponService.down(response, fileName); }
实现类:
public void down(HttpServletResponse response ,String filename) { // 读取要下载的文件,保存到文件输入流 FileInputStream in = null; OutputStream out = null; try { // 得到要下载的文件(文件存放在项目resources的static文件夹里) File file = new File("src\\main\\resources\\static" + "\\" + filename); // 如果文件不存在 if (!file.exists()) { throw new BusinessException("Could not read file"); } // 设置响应头,控制浏览器下载该文件 response.setHeader("Content-Disposition", "attachment;filename="+filename); response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8"); response.setContentType("application/octet-stream"); in = new FileInputStream(file); // 创建输出流 out = response.getOutputStream(); // 创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; // 循环将输入流中的内容读取到缓冲区当中 while ((len = in.read(buffer)) > 0) { // 输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } // 关闭文件输入流 in.close(); // 关闭输出流 out.close(); } catch (Exception e) { e.printStackTrace(); } }
cxxyjsj