There might be a situation where a service needs to produce a CSV (
Comma-separated values) file as output. It should allow for the file to be downloaded – e.g. prompt the user to save the file.

Version: Spring version 5.1.5.RELEASE

There is no media type for “text/csv”. Not to worry, the MediaType class does provide a method to create one by parsing a String into a MediaType via parseMediaType(java.lang.String mediaType).

HttpMediaTypeNotAcceptableException: Could not find acceptable representation

  • Note: Whenever specifying a content type, if it is incorrectly typed (in cases were the constant types could have been used) or is not supported then there will be an exception.

The return type needs to resolve to a file, we can use FileSystemResource to wrap the file returned from the service. Simple example:

@GetMapping(value = "/report/{reportName}", produces = "text/csv")
public ResponseEntity generateReport(@PathVariable(value = "reportName") String reportName) {
    try {
        File file = getReportService().generateReport(reportName);

        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=" + reportName + ".csv")
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("text/csv"))
                .body(new FileSystemResource(file));
				
    } catch (ReportServiceException ex) {
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Unable to generate report: " + reportName, ex);
    } 
}

Leave a comment

Your email address will not be published. Required fields are marked *