赞
踩
笔主本来直接通过File去实现下载功能,打成jar后发现,File寻找文件是找不到的,因为文件是打到jar包中的,jar本身是一个文件,文件中是无法通过file进入目录获取的,只能通过类加载器加载资源得到流,对流进行处理。 所以采用了如下的办法改造代码,实现文件下载功能。
如下是错误代码案例:(本地的开发环境可以下载,但是打出jar包却不能下载)
@RequestMapping("/download") public void download(String type, HttpServletResponse response) { try { String path=""; if ("example".equals(type)) { path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/assets/download/xxx1.excel"; }else if("readMe".equals(type)){ path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/assets/download/xxx2.excel"; }else{ return; } // path是指想要下载的文件的路径 File file = new File(path); // 获取文件名 String filename = file.getName(); // 获取文件后缀名 String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); // 将文件写入输入流 FileInputStream fileInputStream = new FileInputStream(file); InputStream fis = new BufferedInputStream(fileInputStream); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.setCharacterEncoding("UTF-8"); //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存 //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3" // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); // 告知浏览器文件的大小 response.addHeader("Content-Length", "" + file.length()); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); outputStream.write(buffer); outputStream.flush(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { throw new RuntimeException(e); } }
正确的代码如下:
@RequestMapping("/download") public void download(String type, HttpServletResponse response) { try { InputStream is = null; String filename=""; if ("example".equals(type)) { is = getClass().getResourceAsStream("/static/assets/download/xxx1.excel"); filename="xxx1.excel"; }else if("readMe".equals(type)){ is = getClass().getResourceAsStream("/static/assets/download/xxx2.excel"); filename="xxx2.excel"; }else{ return; } if(Objects.isNull(is)) { return; } response.setCharacterEncoding("UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); byte[] buffer = new byte[1024]; int i; ServletOutputStream os = response.getOutputStream(); while ((i = is.read(buffer, 0, buffer.length)) != -1) { os.write(buffer, 0, i); } is.close(); os.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { throw new RuntimeException(e); } }
最终实现文件下载功能。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。