码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC文件下载

时间:2017-09-03 17:09:44      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:str   col   code   ext   tty   jquery   gets   while   java   

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;
    }

 

SpringMVC文件下载

标签:str   col   code   ext   tty   jquery   gets   while   java   

原文地址:http://www.cnblogs.com/deolin/p/7469963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!