Spring MVC 下载文件

流程

  1. 首先 请求方式 使用GET.
  2. 设置Http header。
  3. 将生成的内容转换成byte,浏览器就会根据header里面的信息,将文件保存起来.

代码

/**
     * 导出用户
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "exportAudiences", method = RequestMethod.GET) //请求路径
    public ResponseEntity<byte[]> exportAudiences() throws IOException {
        List<Audience> audiences = audienceService.getAllAudiences(); // 获取需要输出的信息
        ByteArrayOutputStream output = new ByteArrayOutputStream(); //用于转换byte

        HSSFWorkbook wb = ExcelUtil.exportAudience(audiences); //生成一个excel
        if (wb != null) {
            wb.write(output);
        }
        byte[] bytes = output.toByteArray();
        HttpHeaders httpHeaders = new HttpHeaders(); //设置header
        httpHeaders.add("Accept-Ranges", "bytes");
        httpHeaders.add("Content-Length", bytes.length + "");
        httpHeaders.add("Content-disposition", "attachment; filename=allAudience.xls");
        httpHeaders.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, httpHeaders, HttpStatus.CREATED);
        return responseEntity;
    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,915评论 18 139
  • 流程 首先 请求方式 使用GET. 设置Http header。 将生成的内容转换成byte,浏览器就会根据hea...
    一路摇到顶阅读 583评论 0 1
  • 1、第一种情况下载时如果文件名存在中文则需要进行编码String downloadFileName = new S...
    Kx_阅读 1,673评论 0 0
  • 我坐在车里。车向着狂奔,风景向后,天空中的火烧云一动不动。天色慢慢变暗,路上的车尾灯交替着闪烁,车开始多了。每条路...
    赵着急_阅读 170评论 0 4
  • @所有人密码2019 第三天任务:扑克牌对对碰游戏 取相应年龄的扑克牌对数,把所有牌翻过来打乱,让孩子先后拿两张,...
    涵宝妈妈么么哒阅读 181评论 0 0