Home > other >  Spring Boot: No converter for [class java.io.ByteArrayOutputStream]
Spring Boot: No converter for [class java.io.ByteArrayOutputStream]

Time:07-28

I'm trying to export a document from Google Drive via their Drive API, and there's an example of it in the docs, but I didn't have any luck with it.

Here's my code:

@RequestMapping(value = "/test", method = RequestMethod.GET, produces = MediaType.APPLICATION_PDF_VALUE)
public ByteArrayOutputStream downloadSlidesAsPdf(@RequestParam String fileId) throws IOException {
    OutputStream outputStream = new ByteArrayOutputStream();
    driveService.files().export(fileId, "application/pdf").executeMediaAndDownloadTo(outputStream);

    return (ByteArrayOutputStream) outputStream;
}

Executing this results in a warning in the console:

WARN  o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.io.ByteArrayOutputStream] with preset Content-Type 'null']

I tried doing something like adding HttpServletResponse in the request and setting the content type to application/pdf and setting the output stream as such:

driveService.files().export(copiedFile.getId(), "application/pdf")
            .executeMediaAndDownloadTo(response.getOutputStream());

This works, but it downloads the file without the extension, and besides, I'd rather have it work as it's designed to than with a bunch of unnecessary workarounds.

I also tried a midway solution in which I set the HttpServletResponse content-type type to application/pdf, and then try to return the ByteArrayOutputStream like in the first attempt, but no luck. Anyone know what I'm missing here?

CodePudding user response:

The problem is there is nothing to convert in OutputStream - we only write to OutputStream, but do not read.

If controller needs to return binary content, the options are following:

  • byte[]
  • org.springframework.core.io.Resource (InputStreamResource, ByteArrayResource, FileSystemResource, etc)
  • org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody - my own preference
  • Related