2

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

My code runs until the end but it doesn't download anything. It just prints the data to the console.log.

What am I missing here?

My backend controller:

@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();
    }
}

My frontend code:

 $('.generateReport').click(function () {
    var flowName = $(this).attr('name');
   $.ajax({
        url: '/flow/generate-report',
        type: 'get',
        data: {flowName: flowName},
        success: function (data) {
            console.log(data);
        }
    })
});

I get HTTP status 200

HTTP/1.1 200
Content-Disposition: attachment; filename=report-tellerFlow.xlsx
Content-Type: application/xlsx
Transfer-Encoding: chunked
Serban Petrescu
  • 5,127
  • 2
  • 17
  • 34

2 Answers2

0

Content-Type: application/force-download header might not always work because some browsers/web clients might not support the attachment download.

Try changing to Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet which is the correct XLSX type and then check the documentation for your browser/web client. As per this answer using Ajax to download a file might not won't work in your web client.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

I'm not sure that an XHR request can trigger a download dialog on the browser. You might want to spawn a new window instead with the download URL - the browser should detect the content disposition and handle the download accordingly.

If you still want to do it with XHR, you need to use Blobs instead - JavaScript blob filename without link

Nick Caballero
  • 944
  • 1
  • 8
  • 19