zoukankan      html  css  js  c++  java
  • Servlet中使用response对象下载实现

    1,ResponseDownload.java Serlvet实现下载代码:

        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;  
          
        public class ResponseDownload extends HttpServlet {  
            public void doGet(HttpServletRequest request, HttpServletResponse response)  
                    throws ServletException, IOException {  
                //String realpath = this.getServletContext().getRealPath("/2.jpg");//获得下载图片路径  
                String realpath = this.getServletContext().getRealPath("/图片.jpg");//中文名称文件  
             String filename = realpath.substring(realpath.lastIndexOf("\\") + 1);//截取路径获得下载文件名  
            response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));//中文名称文件的下载  
             //response.setHeader("content-disposition", "attachment;filename="+filename);//response 响应头响应下载请求  
             FileInputStream in =new FileInputStream(realpath); //将图片文件以流写入  
    int len=0; byte buffer[]=new byte[1024]; OutputStream out = response.getOutputStream();
    while((len=in.read(buffer))>0){ //读取文件模板代码 ,需记住    out.write(buffer, 0, len);
        }
         in.close();
    }  
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
      }
    }
  • 相关阅读:
    进程与线程(二) java进程的内存模型
    进程学习(一) 进程的地址空间
    在一个数组中除两个数字只出现1次外,其它数字都出现了2次
    倒水问题
    leecode 树是否是平衡树 java
    Max Sum
    Encoding
    海阔天空-
    Binomial Showdown
    Square
  • 原文地址:https://www.cnblogs.com/lichone2010/p/3127857.html
Copyright © 2011-2022 走看看