0

I'm making an ajax call from a jsp to a servlet.

var xhr = new XMLHttpRequest();
function download(){
    xhr.open("GET", "/FileDownloader?<params>");
    xhr.send();
}

In the servlet, I'm creating an Excel file (POI HSSFWorkbook) and can successfully write the xls to a file but cannot send it back to the browser as a download:

private void ResultsXLS(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    resp.setContentType("application/vnd.ms-excel");
    resp.setHeader("Expires", "0");
    resp.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    resp.setHeader("Pragma", "public");
    resp.setHeader("Content-Disposition", "attachment; filename=export.xls");

    try{
        //Datbase query - populates workbook
        HSSFWorkbook wb = new HSSFWorkbook();

        //THIS WORKS - Excel file is flawless
            //try (FileOutputStream outputStream = new FileOutputStream("C:/TEMP/ic50s.xls")){
            //wb.write(outputStream)
            //outputStream.close();

        //THIS DOESN'T WORK
        ServletOutputStream out = resp.getOutputStream();   
        wb.write(out);
        out.flush();
        out.close();
    }
    catch (Exception e) {
        LOG.log(Level.SEVERE, e.toString(), e );
    } finally {
        //cleanup
    }
}

I don't see any errors anywhere. How can I further debug?

Thank you!

mrcrag
  • 310
  • 3
  • 16
  • You need add some more context -- maybe a simplified version of your servlet that's actually responding. My first through though, is that you need to make sure that you're setting the response headers correctly. – lscoughlin Aug 01 '18 at 17:23
  • Thanks, I've added more context. I'm setting the response headers as shown. – mrcrag Aug 01 '18 at 17:39
  • Define "doesn't work", precisely. What are you doing, what do you expect to happen, and what happens instead? – JB Nizet Aug 01 '18 at 17:41
  • 1
    See this answer. https://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request – lscoughlin Aug 01 '18 at 17:50
  • Does wb have a close method? What happens if you call that before closing the stream? – Don Branson Aug 01 '18 at 17:50
  • Note that since you're sending an AJAX request, you're the one responsible to handle the response using JavaScript code. The browser won't open the file (if that's what you expect to happen). – JB Nizet Aug 01 '18 at 17:51
  • Thanks for the link, lscoughlin. A simple window.location has resolved this. – mrcrag Aug 01 '18 at 18:03

0 Answers0