您当前的位置: 首页 >  spring

SpringMVC 下载文件(直接在浏览器打开)

杨林伟 发布时间:2019-06-06 11:08:34 ,浏览量:5

前端代码:

  //下载用户手册
    function downUserManual() {
        debugger
        var downLoadPath = "/system/downUserManual.do";
        var url = getRootPath() + downLoadPath;
        window.open(url)

后端代码:

@RequestMapping(value = "/downUserManual.do", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        FileInputStream fis = null;
        byte[] bytes = null;
        ServletOutputStream ouputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            ServletContext servletContext = request.getSession().getServletContext();
            String filePath = servletContext.getRealPath("/downloadfile/用户手册.pdf");
            File file = new File(filePath);

            fis = new FileInputStream(file);
            baos = new ByteArrayOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            bytes = baos.toByteArray();
            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);
            ouputStream = response.getOutputStream();
            ouputStream.write(bytes, 0, bytes.length);
            ouputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 5浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.1553s