我爱编程

Spring MVC 下载文件

2018-04-15  本文已影响519人  一路摇到顶

流程

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

上一篇下一篇

猜你喜欢

热点阅读