如何从Servlet使用保存文件对话框? [英] How to use a save file dialog from a servlet?
问题描述
我试图让用户将我的servlet中的数据另存为CSV文件.最初,我只是在他们的桌面上放置该文件,但是此路由将拒绝其权限,因此我想询问用户要将文件保存在何处.
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.
根据我所看到的,我无法在servlet中使用Swing API,因为Tomcat不知道如何绘制GUI.我尝试了这段代码:
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());
}
}
但这会引发headlessException.
But this will throw a headlessException.
任何有关如何在Servlet中实现诸如保存文件对话框之类的指导的信息,将不胜感激.
Any guidance on how to implement something like a save file dialog in a servlet would be appreciated.
推荐答案
只需将其写入响应正文,而不是本地(!!)磁盘文件系统.
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.
Content-Disposition: attachment
标头负责处理另存为魔术.
这篇关于如何从Servlet使用保存文件对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!