标签:
第一种方法使用 HttpMessageConverter 下的 ResponseEntity<> 实现。
@RequestMapping("/testHttpMessageDown") public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{ String filename = "123.jpg"; //根据不同浏览器处理下载时文件名乱码问题 if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { filename = URLEncoder.encode(filename, "UTF-8"); } else { filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); } byte[] body = null; InputStream is = request.getSession().getServletContext().getResourceAsStream("/upload/user/JSON.jpg"); body = new byte[is.available()]; is.read(body); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attchement;filename=" + filename); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode); return entity; }
第二种方法是常用的文件下载方式
@RequestMapping("/testFileDown") public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException{ String filename = "这是中文名称123abc()()-234十几分.pdf"; //根据不同浏览器处理下载时文件名乱码问题 if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { filename = URLEncoder.encode(filename, "UTF-8"); } else { filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); } // response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;fileName="+filename); InputStream is = request.getSession().getServletContext().getResourceAsStream("/upload/user/中文名称的文件名.pdf"); OutputStream os = response.getOutputStream(); byte[] b = new byte[1024]; int length = 0; while((length = is.read(b)) > 0){ os.write(b); } os.flush(); os.close(); is.close(); }
标签:
原文地址:http://www.cnblogs.com/yjtx/p/4442245.html