Rest API 端点,用于使用从数据库收集的数据生成 CSV 文件

Rest API endpoint for generating CSV file with data gathered from DB

坚持以反应方式从数据库收集的数据列表中编写 CSV 文件。

我的控制器:

@RestController
@RequestMapping("/v1/foo")
@RequiredArgsConstructor
public class FooController {

    private final FooService paymentService;

    @GetMapping(value = "/export")
    @Validated
    public Mono<ResponseEntity> export(FooQuery query) {
        return fooService.export(query) // return Flux<Foo>
                             .collectList()
                             .map(foos -> ResponseEntity.ok()
                                                        .contentType(MediaType.valueOf("text/csv"))
                                                        // Somehow I need to generate CSV format resource and pass it to body(), but no clue how to do that.
                                                        .body(foos));
    }

}

如何生成 CSV 格式的资源并将其传递给 body()?

解法:

@GetMapping(value = "/export", produces = {"text/csv"})
    @Validated
    public Mono<ResponseEntity> export(FooQuery query) {
        return fooService.export(query) // return Flux<Foo>
                             .collectList()
                             .map(foos -> ResponseEntity.ok()
                                                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=export.csv")
                                                        .body("ffd;fdfddf;ddddd;")); 
                                                        // Need to convert List<Foo> to correct csv string that it'll work otherwise 406 NOT_ACCEPTABLE "Could not find acceptable representation"
    }

获得字符串 csv 后 我正在使用 HttpServletResponse 对象而不是像这样的 ResponseEntity:

 response.addHeader("Access-Control-Expose-Headers", "content-disposition, Content-Type");
            response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + filename);
            response.setContentType("text/csv");
            OutputStream out = response.getOutputStream();
            out.write(csv.getBytes());
            out.flush();