• 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;
        }
  • 相关阅读:
    计算数组的逆序对个数
    处理类型(typedef,uisng,auto,decltype)
    constexpr与常量表达式(c++11标准)
    const的限定
    void*类型的指针
    linux终端拖动鼠标总是产生ctrl+c
    Linux hrtimer分析(2)
    Linux hrtimer分析(一)
    Alarm(硬件时钟) init
    第十一章 Android 内核驱动——Alarm
  • 原文地址:https://www.cnblogs.com/deolin/p/7469963.html
Copyright © 2020-2023  润新知