赞
踩
有时候我们会下载服务器文件,需要将文件返回:
/** * 文件下载 * * @param fileName * @param request * @param response * @throws Exception * @PathVariable注解参考https://www.cnblogs.com/williamjie/p/9139548.html */ @ApiOperation("文件下载") @PostMapping("/download/{fileName}.log") public void download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); //fileName为传入的要下载的文件的文件名,本示例下载的是日志文件所以后缀是.log fileName = URLDecoder.decode(fileName, "UTF-8"); //要下载的文件的路径 File logFile = new File("/usr/local/jar/log/" + fileName + ".log"); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(logFile)); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) { long fileLength = logFile.length(); response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { logger.error("错误信息: ", e); } }
如果使用commons上面代码可简化代码如下:
org.apache.commons.io的maven如下:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
简化代码:
/** * 文件下载 * * @param fileName * @param request * @param response * @throws Exception * @PathVariable注解参考https://www.cnblogs.com/williamjie/p/9139548.html */ @ApiOperation("文件下载") @PostMapping("/download/{fileName}.log") public void download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception { //fileName为传入的要下载的文件的文件名,本示例下载的是日志文件所以后缀是.log fileName = URLDecoder.decode(fileName, "UTF-8"); //要下载的文件的路径 File logFile = new File("/usr/local/jar/log/" + fileName + ".log"); InputStream in = new FileInputStream(logFile); String filenamedisplay = URLEncoder.encode(fileName + ".log", "UTF-8"); response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + filenamedisplay); response.setContentType("application/x-download;charset=utf-8"); OutputStream out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); in.close(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。