java文件下载

时间:2021-05-24 00:28:07   收藏:0   阅读:0
@RequestMapping(value = "/downfile", method = RequestMethod.GET)
    public void downfile(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fileName = request.getParameter("fileName");
            String newPath = request.getSession().getServletContext().getRealPath("") + File.separator
                     + fileName;
            LoggerUtil.info(this.getClass(),"【获取到打印模板】:"+newPath);
            File file = new File(newPath);
            if (!file.exists()) {
                response.getWriter().write("<font color=‘red‘>系统打印异常,请联系管理员</font>");
                return;
            }
            String fileNameShow = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
            FileInputStream is = new FileInputStream(file);
            // 设置相应的头部
            response.addHeader("pragma", "NO-cache");
            response.addHeader("Cache-Control", "no-cache");
            response.addDateHeader("Expries", 0);
            response.setContentType("application/x-download;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNameShow, "UTF-8"));
            IOUtils.copy(is, response.getOutputStream());
            is.close();
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "模板打印异常" + e, e);
            try {
                response.getWriter().write("<font color=‘red‘>系统打印异常,请联系管理员</font>");
            } catch (IOException e1) {
                LoggerUtil.error(this.getClass(), "response写出异常" + e1, e1);
            }
        }finally {
            
        }
    }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!