码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC文件下载

时间:2018-08-12 14:00:38      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:ret   new   数据   fileinput   project   request   文件下载   etc   return   

    @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文件下载

标签:ret   new   数据   fileinput   project   request   文件下载   etc   return   

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

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