浏览器通过下载来下载文件

如图:通过以下方式下载


在jsp页面访问地址:


//执行模版下载
   function downloadTemplate(){
        window.location.href = "download/downloadServlet.do";
    }; 


servlet请求:


package com.xjw.bmp.servlet;


import java.io.IOException;
import java.net.URLDecoder;

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

import com.xjw.bmp.utils.FileDownload;

public class DownloadServlet extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    

    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse resp)
            throws ServletException, IOException {
            
            FileDownload fileDownload = new FileDownload(getServletContext(), resp);
        
            String path=this.getServletContext().getClassLoader().getResource("/").getPath();
            String fileName=path+"excel/如风达信息导入模版.xlsx";
            //logger.debug("请求下载的文件名+路经:" + fileName);
            fileDownload.downloadFile(fileName);
        

    }

}



执行下载的方法类:



package com.xjw.bmp.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;



/**
 * 文件下载, 通过HTTP协议下载文件。
 *
 *
 */

public class FileDownload {
    

    protected HttpServletResponse response;
    protected ServletContext application;
    private String contentDisposition;

    /**
     * 创建类型FileDownload的实例
     *
     * @param application
     *            ServletContext类型的实例
     * @param response
     *            HttpServletResponse类型的实例
     */
    public FileDownload(ServletContext application, HttpServletResponse response) {
        this.response = response;
        this.application = application;        
    }
    /**
     * 设置下载文件内容部署信息
     *
     * @param contentDisposition
     *            部署信息
     */
    public void setContentDisposition(String contentDisposition) {
        this.contentDisposition = contentDisposition;
    }

    /**
     *下载文件
     *
     * @param sourceFilePathName
     *            源文件名,包含文件路径名
     */
    public void downloadFile(String sourceFilePathName) {
        downloadFile(sourceFilePathName, null, null);
    }

    /**
     * 下载文件
     *
     * @param sourceFilePathName
     *            源文件名,包含文件路径名
     * @param contentType
     *            内容类型
     */
    public void downloadFile(String sourceFilePathName, String contentType) {
        downloadFile(sourceFilePathName, contentType, null);
    }

    /**
     * 下载文件
     *
     * @param sourceFilePathName
     *            源文件名,包含文件路径名
     * @param contentType
     *            内容类型
     * @param destFileName
     *            目标文件名名称
     */
    public void downloadFile(String sourceFilePathName, String contentType,
            String destFileName) {
        downloadFile(sourceFilePathName, contentType, destFileName, 65000);
    }

    /**
     * 下载文件
     *
     * @param sourceFilePathName
     *            源文件名,包含文件路径名
     * @param contentType
     *            内容类型
     * @param destFileName
     *            目标文件名名称
     * @param blockSize
     *            一次下载的文件块大小,单位字节
     */
    public void downloadFile(String sourceFilePathName, String contentType,
            String destFileName, int blockSize) {

        if (sourceFilePathName == null || sourceFilePathName.trim().equals("")) {
        //    logger.error("文件 '" + sourceFilePathName + "' 没有找到.");
            throw new IllegalArgumentException("文件 '" + sourceFilePathName
                    + "' 没有找到.");
        }
        ServletOutputStream servletoutputstream = null;
        BufferedOutputStream bufferedoutputstream = null;
        FileInputStream fileIn = null;
        try {
            //logger.debug("文件名:"+sourceFilePathName);
            File file = new File(sourceFilePathName);
            fileIn = new FileInputStream(file);
            long fileLen = file.length();
            int readBytes = 0;
            int totalRead = 0;
            byte b[] = new byte[blockSize];

            if (contentType == null || contentType.trim().length() == 0) {
                response.setContentType("application/x-msdownload");
            } else {
                response.setContentType(contentType);
            }
            // contentDisposition = null;
            contentDisposition = contentDisposition != null ? contentDisposition
                    : "attachment;";

            if (destFileName == null || destFileName.trim().length() == 0) {
                response.setHeader("Content-Disposition", contentDisposition
                        + " filename="
                        + toUtf8String(getFileName(sourceFilePathName)));

            } else {
                response.setHeader("Content-Disposition", String
                        .valueOf((new StringBuffer(String
                                .valueOf(contentDisposition))).append(
                                " filename=")
                                .append(toUtf8String(destFileName))));

            }
            servletoutputstream = response.getOutputStream();
            bufferedoutputstream = new BufferedOutputStream(servletoutputstream);

            while ((long) totalRead < fileLen) {
                readBytes = fileIn.read(b, 0, blockSize);
                totalRead += readBytes;
                bufferedoutputstream.write(b, 0, readBytes);
            }
            fileIn.close();
        } catch (Exception e) {
            //logger.error(e.getMessage());
            e.printStackTrace();    
        } finally {
            /* 关闭bufferedoutputstream */
            if (bufferedoutputstream != null) {
                try {
                    bufferedoutputstream.close();
                } catch (IOException e1) {
                    //logger.error("关闭BufferedOutputStream时发生异常.", e1);
                    e1.printStackTrace();
                }
            }
            /* 关闭fileIn */
            if (fileIn != null) {
                try {
                    fileIn.close();
                } catch (IOException e1) {
                //    logger.error("关闭FileInputStream时发生异常.", e1);
                    e1.printStackTrace();
                }
            }
        }

    }

    /**
     * 返回文件名称
     *
     * @param filePathName
     * @return
     */
    private String getFileName(String filePathName) {
        int pos = 0;
        pos = filePathName.lastIndexOf('/');
        if (pos != -1)
            return filePathName.substring(pos + 1, filePathName.length());
        pos = filePathName.lastIndexOf('\\');
        if (pos != -1)
            return filePathName.substring(pos + 1, filePathName.length());
        else
            return filePathName;
    }

    /**
     * 将串编码为UTF-8格式的URI统一编码格式,如:空格,编码后为%20
     *
     * @param s
     * @return
     * @throws UnsupportedEncodingException
     */
    private String toUtf8String(String s) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                b = String.valueOf(c).getBytes("utf-8");
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值