1、文件下载接口
/** * 下载附件接口 * */ @OpdSkip @RequestMapping(value = "/downloadFile",method = RequestMethod.GET) public CommonResponse<Boolean> downloadFile(String address, HttpServletRequest request, HttpServletResponse response) throws IOException{ System.out.println("address:"+address); if(address == null){return CommonResponse.FAIL(500,"附件下载地址为空");} DownloadHelper.setting(request, response, "application/x-img;charset=UTF-8", address); return cveHoleManageService.downloadFile(address,request,response); }
2、DownloadHelper类
/** * @author: zuowuliu * @Data: 2020/8/18 16:54 */ public class DownloadHelper { public static String formatName(HttpServletRequest request, String fileName) { try { if (request.getHeader("User-Agent").toUpperCase().indexOf("TRIDENT") > 0) { return URLEncoder.encode(fileName, "UTF-8"); } else { return new String(fileName.getBytes("UTF-8"), "ISO8859-1"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } /** * 兼用一切浏览器 * * @param request * @param response * @param contentType * @param fileName * @throws IOException */ public static void setting(HttpServletRequest request, HttpServletResponse response, String contentType, String fileName) throws IOException { String enFileName = formatName(request, fileName); response.setHeader("Content-Disposition", String.format("attachment; filename=%s", enFileName)); response.setCharacterEncoding("UTF-8"); if (StringUtils.isNotBlank(contentType)) { response.setContentType(contentType); } } }
3、download方法
//下载附件 public CommonResponse<Boolean> downloadFile(String address, HttpServletRequest request, HttpServletResponse response) throws IOException{ //由于下载的这个地址本身就是绝对的存储的地址 File file1 = new File(address); OutputStream os = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file1); DataInputStream dataInputStream = new DataInputStream(fileInputStream); int r; while((r=dataInputStream.read())!=-1) { os.write(r); } System.out.println("已下载..."); fileInputStream.close(); dataInputStream.close(); return CommonResponse.OK(true); }