Reputation: 847
I am developing a web app that in some moment the user requests something for the server (servlet) and the server should return a csv file to the user. I need at this point a dialog box appears to the user, giving you the option to specify the directory where you want to save the csv file.
In Servlet I have:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/csv");
response.setHeader("content-disposition","filename=test.csv"); // set the file name to whatever required..
PrintWriter out = response.getWriter();
out.println("a,b,c,d,e,f");
out.println("1,2,3,4,5,6");
out.flush();
out.close();
}
In javascript I have:
$.get('URL_SERVLET' , function(data) {
alert("ret: " + data);
});
How is the next step?
EDIT:
I got a good result using the simple following command:
<a href='http://localhost:8080/MY_SERVLET'> link here </ a>
Clicking on the link, the file test.csv is automatically downloaded
To Answer my need, I need that "href" content was dynamic and was fired by the click of a button.
example:
User select radio component with name "radio 1" and clicked the button "Export csv", this time the url would be built dynamically, example: "http://localhost:8080/MY_SERVLET/csv1" and the file would be downloaded automatically (equal what happens on the link above that contains the text "link here")
Is possible?
Thanks.
Upvotes: 0
Views: 2414
Reputation: 1109362
You cannot force a Save As dialogue with JavaScript, so you end up with an unuseable response. You need to use window.location
instead of an ajax request.
window.location = 'URL_SERVLET';
Upvotes: 0
Reputation: 7371
There is no possible specify the "directory" for download a file, because:
Possible solutions:
Upvotes: 1
Reputation: 597324
You can't trigger the save-as dialog with ajax. You should simply navigate the browser to the download url. It will detect the proper headers and will show the save-as dialog.
Upvotes: 0