简单的一个小记,随上一篇文章.[地址],只是一个补充.
在使用之前的方式下载文件时,会出现中文文件名乱码.使用下列方式即可解决.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public static HttpServletResponse viewFile(String fileDisplayName,String path, HttpServletResponse response) { try { // path是指欲下载的文件的路径。 File file = new File(path); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String( fileDisplayName.getBytes("gb2312"), "ISO8859-1" )); // 兼容中文文件名. response.addHeader("Content-Length", "" + file.length()); String contentType = java.nio.file.Files.probeContentType(Paths.get(path)); System.out.println("fileName:"+new String(fileDisplayName.getBytes())); response.setContentType(contentType); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; } |