首页 > 编程语言 > 详细

SpringMVC文件下载

时间:2018-08-12 13:22:23      阅读:146      评论:0      收藏:0      [点我收藏+]
    @RequestMapping("/downLoadXlsFile")
    public ResponseEntity<byte[]> downLoadXlsFile(@RequestParam("filePath")String path,HttpServletRequest request) throws IOException{
        String projectPath = request.getSession().getServletContext().getRealPath("");
        String xmlsFilePath = projectPath + "portal\\officeFile\\";
        File xmlsFile = new File(xmlsFilePath+path);
        return buildResponseEntity(xmlsFile);
    }
    
    
    /**
     * 构建下载类
     * @param file
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> buildResponseEntity(File file) {
        byte[] body = null;
        //获取文件
        ResponseEntity<byte[]> response=null ;
        InputStream is = null;
       try {
           is = new FileInputStream(file);
           body = new byte[is.available()];
           is.read(body);
           HttpHeaders headers = new HttpHeaders();
           //设置文件类型
           headers.add("Content-Disposition", "attchement;filename=" + file.getName());
           //设置Http状态码
           HttpStatus statusCode = HttpStatus.OK;
           //返回数据
           response = new ResponseEntity<byte[]>(body, headers, statusCode);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }finally {
            if(null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

 

SpringMVC文件下载

原文:https://www.cnblogs.com/jagng951014/p/9462597.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!