我试图让用户将我的servlet中的数据保存为CSV文件。最初我只是找到他们的桌面来删除文件,但是这条路线的许可将被拒绝,所以我想问用户他们想要保存它的位置。
从我所看到的,我不能在servlet中使用Swing API,因为Tomcat不知道如何绘制GUI。我试过这段代码:
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());
}
}
但这会抛出一个无头的异常。
有关如何在servlet中实现类似保存文件对话框的任何指导将不胜感激。
答案 0 :(得分:2)
只需将其写入响应正文而不是本地(!!)磁盘文件系统。
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
标题会处理另存为魔法。
答案 1 :(得分:1)
您无法从servlet调用JFileChooser
,因为servlet在服务器上运行,而不是在客户端上运行;所有Java代码都在服务器上执行。如果要将文件保存在服务器上,则需要知道要写入的路径。
如果要提示用户的浏览器保存文件,请使用内容处置标题:Uses of content-disposition in an HTTP response header