• servlet通过响应头Content-Disposition实现文件下载效果


    package day08;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
     * 案例【Content-Disposition】-- attachment; filename=aaa.zip 
     * @author Administrator
     *  文件下载效果
     */
    public class ResponseDemo05 extends HttpServlet {
    
    	private static final long serialVersionUID = 4407828089924059971L;
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		/*
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("image/png;charset=utf-8");
    		
    		// 1) 读取本地文件
    		FileInputStream in = new FileInputStream("e:/picture.png");
    		
    		// 2) 写出给浏览器(字节内容)
    		OutputStream out = response.getOutputStream();
    		byte[] buf = new byte[1024];
    		int len = 0;
    		// 边读边写
    		while( (len=in.read(buf)) != -1) {
    			out.write(buf, 0, len);
    		}
    		// 关闭
    		in.close();
    		out.close();
    		*/
    		
    		/**
    		 * 但是我们是想让浏览器把这张图片以下载的方式打开
    		 */
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		
    		File file = new File("e:/图片.png");//                                中文的图片名的话,必须这样进行包装     先通过GBK进行getBytes,然后通过设置新的ISO8859_1
    		response.setHeader("content-disposition", "attachment;filename="+new String(file.getName().getBytes("GBK"),"ISO8859_1"));
    		// 1) 读取本地文件
    		FileInputStream in = new FileInputStream(file);
    		
    		// 2) 写出给浏览器(字节内容)
    		OutputStream out = response.getOutputStream();
    		byte[] buf = new byte[1024];
    		int len = 0;
    		// 边读边写
    		while( (len=in.read(buf)) != -1) {
    			out.write(buf, 0, len);
    		}
    		// 关闭
    		in.close();
    		out.close();
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		
    	}
    
    }
    

  • 相关阅读:
    C# 连接 Oracle 的几种方式
    Mac电脑卸载软件后删除残余图标
    文件监视器数量达到系统限制
    Android实现伸缩弹力分布菜单效果
    XMPP协议实现原理介绍
    Android开发之日历控件实现
    OpenGL开发之旅基础知识介绍
    Android in Mono开发初体验之DataBase
    JAVA实现随机无重复数字功能
    Android实现宫格图片连续滑动效果
  • 原文地址:https://www.cnblogs.com/mzywucai/p/11053526.html
Copyright © 2020-2023  润新知