- 该文为堕落的天使不再来原创。欢迎转载。
- 在尽心web开发时,可能遇到以下几种需求:(disposition配置)
- 希望某类或者某已知MIME 类型的文件(比如:*.gif;*.txt;*.htm)能够在访问时弹出“文件下载”对话框。
- 希望客户端下载时以指定文件名显示。
- 希望某文件直接在浏览器上显示而不是弹出文件下载对话框。
对于上面的需求,使用Content-Disposition属性就可以解决。下面是代码示例:
response.setHeader("Content-disposition", "attachment;filename=" + fileName)。
//Content-disposition为属性名。
//attachment表示以附件方式下载。
如果要在页面中打开,则改为inline。
//filename如果为中文,则会出现乱码。解决办法有两种:
//1、使用fileName = new String(fileName.getBytes(), "ISO8859-1")语句
/* 验证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); }
//2、使用 URLEncoder.encode(fileName,"UTF-8" 语句
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); }
时间: 2024-12-29 06:44:45