3

for downloading a file using Spring, I'm using GET method.

@RequestMapping(value = "/exportar/{tipo}", method = RequestMethod.GET)
@ResponseBody
public void exportar(HttpServletResponse response,@PathVariable TipoEnum tipo) throws IOException{

File file = service.exportar(tipo);

response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName() + ".xls"));
        response.setContentType("application/ms-excel; charset=UTF-8"); 
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }

How can I achieve this using POST? Is this possible?

@RequestMapping(value = "/exportar", method = RequestMethod.POST)
Danilo Lemes
  • 2,342
  • 1
  • 14
  • 16
  • 1
    And it doesnt work when you change it to POST? All what you need is set response header to file. You can found inspiration here: http://stackoverflow.com/questions/16652760/return-generated-pdf-using-spring-mvc – Hrabosch Apr 24 '17 at 16:18
  • `POST` is a method for POSTing data not for receiving them, so I do not think that using `POST` is a good idea to downloading files. – noname Feb 25 '20 at 11:53
  • agree with you @noname – Bhaumik Thakkar Feb 25 '20 at 13:50

2 Answers2

0

I just reproduced this error in from within the Insomnia REST client.
Once I added the header:

'Content-type': 'application/json'

The problem seemed to be resolved.

Stephen Paul
  • 37,253
  • 15
  • 92
  • 74
0

Below is my sample working code, I am using ResponseEntity, it can be done without that also.

@PostMapping("/document/{documentId}")
@Timed
public ResponseEntity<byte[]> getDocumentById(@Valid @PathVariable Long documentId, ) throws MalformedURLException {
        return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=" + caseId.toString().concat("_Document.pdf")).body(superBillGenerator.generateSuperBill(caseId, type));
}

It was earlier a GET call, but also works fine with POST.

Bhaumik Thakkar
  • 580
  • 1
  • 9
  • 28