加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

【java工具类】下载文件

发布时间:2020-12-15 05:26:21 所属栏目:Java 来源:网络整理
导读:FileUtil.java /** * 下载文件 * @param file; * @param response */ public static void downloadFile(File file,HttpServletResponse response) { OutputStream os = null ; try { os = response.getOutputStream(); String filePath = file.getName(); if
FileUtil.java
/**
     * 下载文件
     * @param file;
     * @param response
     */
    public static void downloadFile(File file,HttpServletResponse response) {
        OutputStream os  = null;
        try {
            os = response.getOutputStream();
            String filePath = file.getName();
            if(!file.exists()){
                return;
            }

            response.reset();

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,String.format("attachment;filename="%s"",URLEncoder.encode(filePath,"UTF-8")));
            os.write(FileUtils.readFileToByteArray(file));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            IOUtils.closeQuietly(os);
        }
    }

调用:

FileUtil.downloadFile(file,response);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读