java - 如何从 servlet 使用保存文件对话框?

标签 java swing jsp servlets tomcat5.5

我试图让用户将我的 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());
    }



}

但这会抛出 headlessException。

任何关于如何在 servlet 中实现诸如保存文件对话框之类的内容的指导将不胜感激。

最佳答案

只需将其写入响应正文而不是本地(!!)磁盘文件系统。

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 header 负责另存为魔法。

另请参阅:

关于java - 如何从 servlet 使用保存文件对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15483637/

相关文章:

java - Swing Pin 中网格单元的颜色渐变动画

java - 如何使用结果集中的两个字段创建 JSON 数组?

java - 类不会编译 JSP Tomcat

java - 检查 Tomcat 版本

java - 如何将Java静态二维 double 组代码转换为C代码

javascript - 是否可以使用 Java 中基于 Node.JS 的模块?

java - FXML 中的 "Handler method not accessible"错误(仅当我使用 "Event"或 "ActionEvent"参数创建方法时才有效)

java - 为什么 JButton.setBounds 不能在 for 循环中工作?

java - 开发用户界面的最佳 Java 框架是什么?

jsp - Tomcat 7.0.27 不适用于自定义标签