Servlet下载方法 Java

来源:互联网 发布:巴菲特 知乎 编辑:程序博客网 时间:2024/05/22 09:43
第一步:servlet代码

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 页面附件下载
 * @author sxq
 * 只需传入相对的文件路径 属性名为:filePath 如filePath=attached/file/20140327/20140327094258_685.xls
 *
 */

public class Download extends HttpServlet {
    /**
     *
     */

    private static final long serialVersionUID = -1359970931835765041L;

    private static final String CONTENT_TYPE = "application/octet-stream";


    public void init() throws ServletException {
    }
    
    /**
     * 页面附件下载
     * 只需传入相对的文件路径 属性名为:filePath 如filePath=attached/file/20140327/20140327094258_685_servlet下载.xls
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
               
        response.setContentType(CONTENT_TYPE);//设置内容格式
        String filePathTrue=request.getParameter("filePath");
        
        if(request.getParameter("filePath").startsWith("/")){
            filePathTrue=filePathTrue.replace(filePathTrue.substring(0,filePathTrue.indexOf("attached")), "");
        }
        String  filePath=request.getSession().getServletContext().getRealPath("/")+filePathTrue;
        
        //判断下载文件是否包含attached文件夹,防止一些非法下载
        if(!filePath.contains("attached")){
            PrintWriter out =response.getWriter();
            out.print("<script>alert('文件路径不合法');</script>");
            out.flush();
            out.close();
            return ;
        }
        //获取文件名
        String filename=filePath.substring(filePath.lastIndexOf("_")+1);
        //创建file对象
        File file=new File(filePath);
        
        if(!file.exists()){
            PrintWriter out =response.getWriter();
            out.print("<script>alert('文件不存在');</script>");
            out.flush();
            out.close();
            return ;
        }
        
        //写明要下载的文件的大小
        response.setContentLength((int)file.length());
       
        //防止中文文件名过长,或者含有“-”字符时,火狐下载,没有文件格式的情况
        if(filename.length()>17){
            filename=filename.substring(0,15)+"..."+filename.substring(filename.lastIndexOf("."));
        }
        if(filename.contains("-")){
            filename=filename.substring(0, filename.indexOf("-")-1)+"..."+filename.substring(filename.lastIndexOf("."));
        }
        //设置附加文件名  ---解决中文乱码
        filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
        
        response.setHeader("Content-Disposition","attachment;filename="+filename);       
        
        //读出文件到i/o流
        FileInputStream fis=new FileInputStream(file);
        BufferedInputStream buff=new BufferedInputStream(fis);
        byte [] b=new byte[1024];                
        long k=0;                                //该值用于计算当前实际下载了多少字节
      
        OutputStream myout=response.getOutputStream();
      
        while(k<file.length()){
            int j=buff.read(b,0,1024);
            k+=j;
          
            myout.write(b,0,j);
        }
        //将写入到客户端的内存的数据,刷新到磁盘
        myout.flush();
        myout.close();
        buff.close();
        fis.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    public void destroy() {
    
    }

}



第二步:web.xml 配置

前部分省略,相信一般人看的懂

<servlet>  
        <servlet-name>download</servlet-name>  
        <servlet-class>servlet文件所在位置</servlet-class>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>download</servlet-name>  
        <url-pattern>/download</url-pattern>  
    </servlet-mapping>


第三步:访问

很简单的:就可以用html标签直接访问,比如:

<a  href="web项目名/download?filePath=attached/file/20140327/20140327094258_685_servlet下载.xls">下载</a>

0 0
原创粉丝点击