SpringBoot返回文件给前端

主要代码如下:

/**
 * 通过HttpServletResponse将文件流返回给前端
 *
 * @param response HttpServletResponse在Controller层直接接收即可
 * @param is 需要返回的文件流
 * @param fileName 文件名
 * @return
 */
private static ResponseEntity 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 export(HttpServletResponse httpServletResponse) throws IOException {
    return wisdomScreenService.export(httpServletResponse);
}

你可能感兴趣的:(java,java,后端)