0

Stuck with composing CSV file from list of gathered data from db in reactive way.

My controller:

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

}

How I can generate CSV format resource to pass it to body()?

Solution:

@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"
    }

1 Answer 1

1

once you have the String csv Im using HttpServletResponse object instead the ResponseEntity like that:

 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();
Sign up to request clarification or add additional context in comments.

1 Comment

One hint I got from your suggestion regarding added CONTENT_DISPOSITION, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.