码迷,mamicode.com
首页 > 其他好文 > 详细

下载根目录下的pdf文件, 浏览器下载

时间:2019-12-17 15:22:37      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:bsp   request   pdf   nts   exce   http   打开   null   stack   

 public void outPut(HttpServletRequest request, HttpServletResponse response, Integer type) {
        ClassPathResource classPathResource = new ClassPathResource("pdf/通知.pdf");
        String filename = "通知.pdf";
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            String userAgent = request.getHeader("User-Agent");
            response.setCharacterEncoding("utf-8");
            byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8");
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(bytes, "iso8859-1"));
            bufferedInputStream = new BufferedInputStream(classPathResource.getInputStream());
            //bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] bytes2 = new byte[1024];
            int i = 0;
            while ((i = bufferedInputStream.read(bytes2)) != -1){
                response.getOutputStream().write(bytes2, 0, i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.getOutputStream().flush();
                response.getOutputStream().close();
                //bufferedOutputStream.close();
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 上面的被注销掉的两行代码,在没有注销之前,下载的pdf老是打不开。再去掉包装之后,文件可以正常打开。

下载根目录下的pdf文件, 浏览器下载

标签:bsp   request   pdf   nts   exce   http   打开   null   stack   

原文地址:https://www.cnblogs.com/prader6/p/12054394.html

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