spring mvc 文件下载

参考地址:

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

 

//下载绩效操作手册
    @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");
        

      // 如果使用 springmvc 的方式就是 第三种方式,那么下面的 2行代码要注释掉,否则报错 

//  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);

        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);

        // 第二种下载方式
//        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;
        
        
    }

转载于:https://my.oschina.net/ouminzy/blog/817714

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值