[功能集锦] 001 - java下载文件

吃可爱长大的小学妹 提交于 2019-12-18 16:40:09
    @RequestMapping("/downloadxls.action")
    public void downloadxls(HttpServletRequest request, HttpServletResponse response) {
        //获取请求参数
        Map<String, Object> params = ParamsUtil.getParams(request);
        String contextPath = request.getSession().getServletContext().getRealPath(File.separator + "report");
        String excelName = xxxxx;
        String excelFullName = contextPath + File.separator + excelName + ".xls";
        InputStream inStream = null, fileInStream = null;
        ServletOutputStream outStream = null;
        int byteRead;
        try {
            fileInStream = new FileInputStream(excelFullName);
            inStream = new BufferedInputStream(fileInStream);
            response.reset();
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-disposition", "attachment; filename=" + excelName + ".xls");
            outStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            while ((byteRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, byteRead);
            }
            response.flushBuffer();
            outStream.close();
            inStream.close();
            fileInStream.close();
        } catch (Exception e) {
            LOGGER.error( e);
        }finally{
            try {
                if(outStream!=null){
                    outStream.close();
                }
            } catch (IOException e2) {
                LOGGER.error(e2);
            }
            try {
                if(inStream!=null){
                    inStream.close();
                }
            } catch (IOException e2) {
                LOGGER.error(e2);
            }
            try {
                if(fileInStream!=null){
                    fileInStream.close();
                }
            } catch (IOException e2) {
                LOGGER.error(e2);
            }
        }
    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!