前言 创建一个 Springboot 项目,也可以是普通 Java 项目,前端用 Vue 的 axios 接收下载
一、后端 解析都在注释里
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 @RequestMapping("/download") public void download (HttpServletResponse response) throws Exception { File file = new File ("F:/uploadFiles/test.xlsx" ); response.setCharacterEncoding("UTF-8" ); String realFileName = file.getName(); response.setHeader("content-type" , "application/octet-stream;charset=UTF-8" ); response.setContentType("application/octet-stream;charset=UTF-8" ); response.addHeader("Content-Length" , String.valueOf(file.length())); try response.setHeader("Content-Disposition" , "attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(), "UTF-8" )); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } byte [] buff = new byte [1024 ]; try { OutputStream os = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream (new FileInputStream (file)); int i = bis.read(buff); while (i != -1 ) { os.write(buff, 0 , buff.length); os.flush(); i = bis.read(buff); } }catch (Exception e){ e.printStackTrace(); }finally { if (bis != null ) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
二、前端接收下载 我这里使用的是 axios,你们如果不是需要修改一下,但是下载文件的方法代码都是一样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 download ( ){ const config = { method : 'get' , url : 'http://localhost:19021/api/fwq/fwqProduct/downloadFile' , headers : { 'Content-Type' : 'application/octet-stream;charset=UTF-8' }, responseType : 'blob' }; axios (config).then (response => { const url = window .URL .createObjectURL (new Blob ([response.data ])); const link = document .createElement ('a' ); link.href = url; link.setAttribute ('download' , 'xxxx.pdf' ); document .body .appendChild (link); link.click (); }) },