How to use save file dialog from servlet?

I am trying to allow a user to save data from my servlet as a CSV file. Initially, I just found my desktop to delete the file, but permission will be denied using this route, so I want to ask the user where he wants to save it.

From what I see, I cannot use the Swing API in the servlet because Tomcat does not know how to draw a 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 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 an exception without a header.

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

+2
source share
2 answers

Just write it to the response body, and not 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 eg 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 Save As magic.

See also:

+2
source

You cannot call JFileChooser from a servlet because the servlet is running on the server and not on the client; all your java code is executed on the server. If you want to save the file on the server, you already need to know the path you want to write.

If you want the user browser to save the file, use the content-disposition header: Using content in the HTTP response header

+1
source

Source: https://habr.com/ru/post/977672/


All Articles