码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet文件下载

时间:2017-07-09 23:52:32      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:position   response   throws   ror   读取   inpu   问题   tchar   输出   

<a href="DownLoadServlet">下载</a> <br/>  
public class DownLoadServlet extends HttpServlet {  
  
      
    public DownLoadServlet() {  
        super();  
    }  
  
  
    public void destroy() {  
        super.destroy(); // Just puts "destroy" string in log  
        // Put your code here  
    }  
  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doPost(request,response);  
    }  
  
      
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        //处理请求  
        //读取要下载的文件  
        File f = new File("E:/好久不见.mp3");  
        if(f.exists()){  
            FileInputStream  fis = new FileInputStream(f);  
            String filename=URLEncoder.encode(f.getName(),"utf-8"); //解决中文文件名下载后乱码的问题  
            byte[] b = new byte[fis.available()];  
            fis.read(b);  
            response.setCharacterEncoding("utf-8");  
            response.setHeader("Content-Disposition","attachment; filename="+filename+"");  
            //获取响应报文输出流对象  
            ServletOutputStream  out =response.getOutputStream();  
            //输出  
            out.write(b);  
            out.flush();  
            out.close();  
        }     
          
    }  
  
    /** 
     * Initialization of the servlet. <br> 
     * 
     * @throws ServletException if an error occurs 
     */  
    public void init() throws ServletException {  
        // Put your code here  
    }  
  
}  

 

Servlet文件下载

标签:position   response   throws   ror   读取   inpu   问题   tchar   输出   

原文地址:http://www.cnblogs.com/mrelk/p/7143541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!