0

I found many of the answers in these forums very useful for me but would request you to check this issue of mine.

I'm trying to save a .csv file from a servlet that is called by a jquery method. Though I'm setting the header and the content-diposition. I'm not getting the dialogue box in the browser after stream writing the data.

function popup(data) {
    $.post("cisco-fetch-devices", { orderId : data},
        function(data) {
            alert("Data Loaded: " + data);  
        });
    });
}

The above jquery code is calling the below servlet post method:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    response.setContentType("text/csv");
    response.setHeader ("Content-Disposition", "attachment;filename=\"tableincsv.csv\"");
    java.io.PrintWriter out = response.getWriter();
    out.print("test data");
}

After the data is sent back to the browser, the dialogue box is not displayed. However the data that is set in the servlet out.print is displayed correctly displayed in the alert message of the JS method.

Please give me your inputs on this.

Thanks, aditya

CD Smith
  • 6,597
  • 7
  • 40
  • 66
Aditya R
  • 383
  • 2
  • 7
  • 21

1 Answers1

1

Short answer : you can't do it with AJAX, which ignores Content-Disposition header in order to be able to feed its data object. You have to rely on the browser, which honours this header.

So, do a regular POST (with hidden fields) or GET (with querystring parameters) on your servlet.

Or use this jQuery Plugin, recommended by user Vinodh Ramasubramania on Stackoverflow, to automate the process. Code is very short and does just that...

There are numerous threads on this topic :

Community
  • 1
  • 1
Alain BECKER
  • 787
  • 5
  • 15
  • Thanks a lot for the answer! But can you please help on one more issue?- I'm not able to call the servlet Post method from the dynamically generated form tag: – Aditya R Jun 08 '12 at 11:17
  • Here is the link to that question : http://stackoverflow.com/questions/10948016/not-able-to-call-servlet-dopost-method-from-js-form – Aditya R Jun 08 '12 at 11:36