Util工具类 下载指定路径下的文件

来源:互联网 发布:有什么好的网游知乎 编辑:程序博客网 时间:2024/05/16 05:31
    /**     * 下载指定文件路径fileUrl下的文件     * 生成指定文件格式fileType和指定文件名称fileName     * <p>     * 2017年7月10日 14:58:04     * xj     *     * @param fileName 指定文件名称     * @param fileUrl  指定文件路径     * @param fileType 指定文件格式     * @param response     */    public static void downloadFile(String fileName, String fileUrl, String fileType, HttpServletResponse response) {        InputStream in = null;        try {            //1.获取要下载的文件的绝对路径            File file = new File(fileUrl);            //5.获取要下载的文件输入流            in = new FileInputStream(file);            BufferedInputStream bis = new BufferedInputStream(in);            //2.获取要下载的文件名//            String fileName = excelName;            //3.设置content-disposition响应头控制浏览器以下载的形式打开文件            response.setHeader("conent-type", "application/octet-stream");            response.setContentType("application/octet-stream");            fileName = java.net.URLEncoder.encode(fileName, "utf-8");            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "." + fileType);            //4.通过response对象获取OutputStream流            OutputStream os = response.getOutputStream();            BufferedOutputStream bos = new BufferedOutputStream(os);            //6.创建数据缓冲区            byte[] temp = new byte[1 * 1024 * 10];            //7.将BufferedInputStream流写入到buffer缓冲区            int length;            while ((length = bis.read(temp)) != -1) {                //8.使用OutputStream将缓冲区的数据输出到客户端浏览器                bos.write(temp, 0, length);            }            bos.flush();            bis.close();            bos.close();        } catch (IOException e) {            throw new BaseRuntimeException("download file error.", e);        } finally {            try {                if (in != null) {                    in.close();                }            } catch (IOException e) {                logger.error(e.getMessage(), e);            }        }    }
原创粉丝点击