J. Doe J. Doe - 2 years ago 601
Java Question

How to return binary data instead of base64 encoded byte[] in spring mvc rest controller

I want to return a generated pdf file via spring-mvc-rest controller. This is a shortened version of the code I'm currently using:

public class XController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseEntity<byte[]> find() throws IOException {
byte[] pdf = createPdf();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "pdf"));
headers.setContentDispositionFormData("attachment", "x.pdf");
return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);

This works almost fine, it just to return the actual byte array as base64 encoded :(

curl -i ''

Server: Apache-Coyote/1.1
Content-Disposition: form-data; name="attachment"; filename=x.pdf"
Content-Type: application/pdf
Content-Length: 138654
Date: Fri, 08 Jan 2016 11:25:38 GMT

"JVBERi0xLjYNJeLjz9MNCjMyNCAwIG9iag [...]

(btw. the response doesn't even contain a closing

Any hints appreciated!

Answer Source

I created the example using your code, but a very similar method is doing his job in my web application:

@RequestMapping(value = "/", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response,
                         HttpServletRequest request) throws IOException
    byte[] pdf = createPdf();

    response.setHeader("Content-Disposition", "attachment; filename=foo.pdf");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

Else you can try this answer Open ResponseEntity PDF in new browser tab

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download