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

 

posted @ 2017-09-03 16:44  Deolin  阅读(279)  评论(0编辑  收藏  举报