对于上面的需求,使用Content-Disposition属性就可以解决。下面是代码示例:
/* 验证content-disposition */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = this.getServletContext().getRealPath("/picture/桌面壁纸.jpg"); String fileName = path.substring(path.indexOf("\\") + 1); //1、使用fileName = new String(fileName.getBytes(), "ISO8859-1")语句 fileName = new String(fileName.getBytes(),"ISO8859-1"); // response开始发送响应头 response.setHeader("content-disposition", "attachment;filename=" + fileName); // 基本的流操作 OutputStream out = null; FileInputStream in = null; try { in = new FileInputStream(path);// 绝对路径 out = response.getOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } finally { if (in != null) { try { // 关闭流 in.close(); } catch (Exception e) { e.printStackTrace(); } } if (out != null) { try { // 关闭流 out.close(); } catch (Exception e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = this.getServletContext().getRealPath( "/picture/桌面壁纸.jpg"); String fileName = path.substring(path.lastIndexOf("\\") + 1); // System.out.println(fileName);//桌面壁纸.jpg /*response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8");*///这样是错误的 // 发送响应头,如果文件是中文名,这要经过url编码 response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8")); // 下载图片 OutputStream out = null; FileInputStream in = null; try { in = new FileInputStream(path);// 绝对路径 out = response.getOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } finally { if(in != null){ try{ // 关闭流 in.close(); }catch(Exception e){ e.printStackTrace(); } } if(out != null){ try{ // 关闭流 out.close(); }catch(Exception e){ e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
原文:http://www.cnblogs.com/duoluo-lin/p/5208548.html