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;
        }
  • 相关阅读:
    程序书写规范
    点灯主要顺序
    复用功能重映射
    STM32 (战舰)
    html5 javascript 新增加的高级选择器更精准更实用
    html5 javascript 事件练习3键盘控制练习
    html5 javascript 事件练习3随机键盘
    html5 javascript 事件练习2
    html5 javascript 事件练习1
    html5dom2
  • 原文地址:https://www.cnblogs.com/deolin/p/7469963.html
Copyright © 2011-2022 走看看