How to use a save file dialog from a servlet?

Jason Renaldo picture Jason Renaldo · Mar 18, 2013 · Viewed 7.8k times · Source

I am trying to let the user save data from my servlet as a CSV file. Originally I was just locating their desktop to drop the file, but permission would be denied with this route so I want to ask the user where they want to save it.

From what I am seeing, I cannot use the Swing API in a servlet because Tomcat does not know how to draw the GUI. I tried this code:

    String fileName = "ClassMonitor" + formatter.format(currentDate) + ".csv";

    File csvFile = new File(fileName);

    //Attempt to write as a CSV file 
    try{

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setSelectedFile(csvFile);
        int returnValue = fileChooser.showSaveDialog(null);

        if(returnValue == JFileChooser.APPROVE_OPTION)
        {
            BufferedWriter out = new BufferedWriter(new FileWriter(csvFile));

            //Iterates and writes to file
            for(ClassInfo classes : csvWrite)
            {
                //Check if the class has a comma. Currently, only section titles have a comma in them, so that's all we check for.
                classes.setSectionTitle(replaceComma(classes.getSectionTitle()));

                out.write(classes.toString());
            }

            //Close the connection
            out.close();
        }

        //Log the process as successful.
        logger.info("File was successfully written as a CSV file to the desktop at " + new Date() + "\nFilename" +
                "stored as " + fileName + ".");

    }
    catch(FileNotFoundException ex)
    {
        //Note the exception
        logger.error("ERROR: I/O exception has occurred when an attempt was made to write results as a CSV file at " + new Date());
    }
    catch(IOException ex)
    {
        //Note the exception
        logger.error("ERROR: Permission was denied to desktop. FileNotFoundException thrown.");
    }
    catch(Exception ex)
    {
        //Note the exception
        logger.error("ERROR: Save file was not successfull. Ex: " + ex.getMessage());
    }



}

But this will throw a headlessException.

Any guidance on how to implement something like a save file dialog in a servlet would be appreciated.

Answer

BalusC picture BalusC · Mar 18, 2013

Just write it to the response body instead of to the local(!!) disk file system.

response.setContentType("text/csv"); // Tell browser what content type the response body represents, so that it can associate it with e.g. MS Excel, if necessary.
response.setHeader("Content-Disposition", "attachment; filename=name.csv"); // Force "Save As" dialogue.
response.getWriter().write(csvAsString); // Write CSV file to response. This will be saved in the location specified by the user.

The Content-Disposition: attachment header takes care of the Save As magic.

See also: