zoukankan      html  css  js  c++  java
  • SpringMVC文件下载

    1、pom.xml追加

    javax.servlet-api(Web容器的往往会自带里面的jar文件,追加这个依赖仅仅是为了HttpServletRequest和HttpServletResponse参数不报错)

    2、示例

    HTML

        <a href="/download?mode=1">Download File (absolute path)</a>
        <a href="/download?mode=2">Download File (relative path)</a>

    Java

        /**
         * 测试<br>
         * 下载文件
         *
         * @author Deolin
         */
        @RequestMapping(value = "download", method = RequestMethod.GET)
        public String download(Integer mode, HttpServletRequest request, HttpServletResponse response) {
            String fileName;
            File file;
            if (mode == 1) {
                // 绝对路径文件
                fileName = "hosts";
                file = new File("C:\Windows\System32\drivers\etc\" + fileName);
            } else {
                // 相对路径文件
                fileName = "jquery-3.2.1.min.js";
                file = new File(request.getServletContext().getRealPath("/lib/" + fileName));
            }
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                LOG.error("I/O异常");
                return "redirect:/500";
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        LOG.error("I/O异常");
                        return "redirect:/500";
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        LOG.error("I/O异常");
                        return "redirect:/500";
                    }
                }
            }
            return null;
        }
  • 相关阅读:
    std thread
    windows更新包发布地址
    How to set up logging level for Spark application in IntelliJ IDEA?
    spark 错误 How to set heap size in spark within the Eclipse environment?
    hadoop 常用命令
    windows 安装hadoop 3.2.1
    windows JAVA_HOME 路径有空格,执行软连接
    day01MyBatisPlus条件构造器(04)
    day01MyBatisPlus的CRUD 接口(03)
    day01MyBatisPlus入门(02)
  • 原文地址:https://www.cnblogs.com/deolin/p/7469963.html
Copyright © 2011-2022 走看看