zoukankan      html  css  js  c++  java
  • 使用Servlet实现下载文件的功能

    使用Servlet实现下载文件的功能

    在前台有一个下载链接,比如

    <a href="DownLoadServlet">下载</a> <br/>  


    使用Servlet实现下载:

    复制代码
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
    import java.net.URLEncoder;  
      
    import javax.servlet.ServletException;  
    import javax.servlet.ServletOutputStream;  
    import javax.servlet.http.HttpServlet;  
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpServletResponse;  
      
    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  
        }  
      
    }  
    复制代码

    配置文件注意路径。。。

  • 相关阅读:
    JAVA 作业:图形界面
    操作系统实验3:内存分配与回收
    PLAN :昔日未来
    操作系统课程:调度算法
    KMP 代码 暂存
    笔试总结篇(一) : 广州X公司笔试
    雨夜静思(一)
    KMP算法详解-- 转自Matrix67
    百度笔试
    lucene中Document删除不了的问题
  • 原文地址:https://www.cnblogs.com/jinhengyu/p/10258121.html
Copyright © 2011-2022 走看看