主要代码如下:

/**
 * 通过HttpServletResponse将文件流返回给前端
 *
 * @param response HttpServletResponse在Controller层直接接收即可
 * @param is 需要返回的文件流
 * @param fileName 文件名
 * @return
 */
private static ResponseEntity<InputStreamResource> encapsulateResponseEntities(HttpServletResponse response, InputStream is, String fileName) throws IOException {
    //设置文件格式,我这里是excel,根绝实际应用场景改即可
    response.setContentType("application/msexcel");
    //设置文件名,设置字符集是避免文件名中有中文时出现乱码
    fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
    response.addHeader("Content-Disposition", "filename=" + fileName);
    OutputStream outputStream = response.getOutputStream();
    outputStream.write(is.readAllBytes());
    outputStream.close();
    return null;
}

Controller层(Service层生成文件的代码略去):

@GetMapping("export")
public ResponseEntity<InputStreamResource> export(HttpServletResponse httpServletResponse) throws IOException {
    return wisdomScreenService.export(httpServletResponse);
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐