vctlzac
vctlzac

Reputation: 847

Export csv with Servlet and Javascript

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

Answers (3)

BalusC
BalusC

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

Ernesto Campohermoso
Ernesto Campohermoso

Reputation: 7371

There is no possible specify the "directory" for download a file, because:

  1. The protocol HTTP just enable you to specify the name of the file then you can't suggest the directory from Servlet. Respect where download the file it will depend of browser configuration and this isn't standard
  2. JavaScript don't allow to you write to disk then you can't receive the CSV and later write it to disk.

Possible solutions:

  1. You can use an Applet that contact with the servlet and then write the file to desired directory. If you decide do this then you will need sign the applet.
  2. You can use Flash, ActiveX, etc. (I don't know the details for these aproaches)

Upvotes: 1

Bozho
Bozho

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

Related Questions