0

I want to download a file from from the front end. The file is generated on TestFlow.generateReport

My runs until the end but it doesn't download anything. What am I missing here??

    @RequestMapping(value = "/flow/generate-report" , method = RequestMethod.GET)
public @ResponseBody void generateFlowReport(@RequestParam("flowName") String flowName, HttpServletResponse response) {
    InputStream resource = TestFlow.generateReport(flowName);
    response.setContentType("application/force-download");
    response.setHeader("Content-Disposition","attachment; filename=report-" + flowName + ".xlsx");
    try {
        IOUtils.copy(resource,response.getOutputStream());
        response.flushBuffer();
        resource.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • what is this generate-report? value = "/flow/generate-report" – Cowboy Farnz Feb 28 '18 at 15:01
  • ajax post. It just sends the name of the flow. The generateReport method creates an excel and passes the inputstream to the controller. –  Feb 28 '18 at 15:03
  • have you tried different content types? response.setContentType("application/octet-stream"); for example? – juju Feb 28 '18 at 15:16
  • @juju didnt work –  Feb 28 '18 at 15:18
  • what does your ajax post look like? – juju Feb 28 '18 at 15:20
  • for excel I've been using these content type headers; xls - "application/vnd.ms-excel", xlsx - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet". I generally create a byte [] with files and do: try (OutputStream outStream = response.getOutputStream()) { outStream.write(bytes); outStream.flush(); } – juju Feb 28 '18 at 15:47
  • Shouldn't you have a value like (value = '/flow/{file_name}" , and the @RequestParam, why don'y you use @PathVariable("file_name") String fileName, – Cowboy Farnz Feb 28 '18 at 16:07
  • Also isn't the 'Spring' way to set content type like this? @RequestMapping(value = "/flow/generate-report", produces = "application/force-download", method = RequestMethod.GET) – Cowboy Farnz Feb 28 '18 at 16:08

1 Answers1

0

The original AJAX request can not handle file download request. You must create a virtual form. see this question. And there are lots of jQuery plugin help you to do this.

And since its a download request, your controller method should not use @ResponseBody, take over the response all by yourself, close it after writing the content.

tianzhipeng
  • 2,149
  • 1
  • 13
  • 17