Download bytes docx api Rest

Asked

Viewed 47 times

0

The code shows a method that is called by the browser to generate a PDF. The bytes were generated by Jasper. The code works normally.

@GetMapping("/relatorios/teste")
public ResponseEntity<byte[]> relatorio() throws Exception{
    byte[] relatorio = lancamentoService.relatorio();

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE)
        .body(relatorio);
}

OBS1: My problem is when I have the bytes of a docx! I’ve tried to do something similar to PDF, but I haven’t succeeded yet, I tried several code found on the net and nothing.

OBS2: Docx bytes i Gero using Apache POI.

  • You are using Spring Boot?

1 answer

1

I suggest some changes to your download scheme, the second is not mandatory but I recommend it anyway:

  1. Utilize MediaType.APPLICATION_OCTET_STREAM since you work with several formats, this type is considered an arbitrary data according to RFC2046 and will serve in this case.
  2. Add the property to the header to avoid caching no-cache (non-compulsory)

And finally update your code to build the ResponseEntity in this way:

@GetMapping("/relatorios/teste")
public ResponseEntity<byte[]> relatorio() throws Exception {
    return new ResponseEntity<>(lancamentoService.relatorio(), getConfiguredAttachmentHeaders(), HttpStatus.OK);
}

private HttpHeaders getConfiguredAttachmentHeaders() {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setCacheControl(CacheControl.noCache().getHeaderValue());
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return httpHeaders;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.