业务场景:点击一个链接进行下载文件,浏览器自动下载。不是在线打开。
/** * 点击下载文件使用 * * @param response * @param fileName * @param request * @throws IOException */ @RequestMapping(value = "/batch/dl", method = RequestMethod.GET) @ResponseBody public void testDownload(HttpServletResponse response, String fileName, HttpServletRequest request) throws IOException { //根据文件名称获取服务器上的文件 File downloadFile = new File(fileName); ServletContext context = request.getServletContext(); String mimeType = context.getMimeType(fileName); if (mimeType == null) { mimeType = "application/octet-stream; charset=ISO8859-1"; System.out.println("context getMimeType is null"); } response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", new String(downloadFile.getName().getBytes("ISO8859-1"))); response.setHeader(headerKey, headerValue); try { InputStream myStream = new FileInputStream(fileName); //装载文件 OutputStream outputStream = response.getOutputStream(); IOUtils.copy(myStream, outputStream); response.setCharacterEncoding("utf-8"); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } }