spring mvc 文件下载

参考地址:java

http://www.jb51.net/article/84691.htmspring

 

//下载绩效操做手册
    @RequestMapping("/down/pfmceplan.do")
    public ResponseEntity<byte[]> downPfmceplan(HttpServletRequest request,HttpServletResponse response) throws Exception{
        
        String fileName="绩效操做shouceV1.0.zip";
        
        response.reset();
        response.setCharacterEncoding("utf-8");
        mvc

      // 若是使用 springmvc 的方式就是 第三种方式,那么下面的 2行代码要注释掉,不然报错 app

//  connetct reset()...链接错误 ,有冲突
        //response.setContentType("application/octet-stream; charset=utf-8");
        //response.setHeader("Content-Disposition", "attachment; filename="
        //        + fileName);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);this

        String path = Thread.currentThread().getContextClassLoader()
                .getResource("").getPath();
        // 求出 根项目的路径
        String pathRealroot=path.substring(0, path.lastIndexOf("WEB-INF"))+"assets/"+"download/";        
        
        File downPath=new File(pathRealroot
                +File.separator + fileName);
        
        System.out.println("=================>>>>>>>>>>>>>>>"+downPath);
        
        // 第三种 下载方式
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downPath), 
                headers, HttpStatus.CREATED);.net

        // 第二种下载方式
//        OutputStream os = response.getOutputStream();
//        os.write(FileUtils.readFileToByteArray(downPath));
//        os.flush();
//        os.close();
        //return null;
        
        /*
         * 原生下载方式 第一种
         * InputStream inputStream = new FileInputStream(downPath);
         * 
         * 
         * 
         * 
         * 
         * byte[] b = new byte[2048]; int length; while ((length =
         * inputStream.read(b)) > 0) { os.write(b, 0, length); } os.flush();
         * 
         * // 这里主要关闭。 os.close();
         * 
         * inputStream.close();
         */
        
        
        // 返回值要注意,要否则就出现下面这句错误!
        // java+getOutputStream() has already been called for this response
        //return null;
        
        
    }orm

相关文章
相关标签/搜索