【问题标题】:How to use a save file dialog from a servlet?如何使用 servlet 中的保存文件对话框?
【发布时间】:2013-03-18 17:56:34
【问题描述】:

我试图让用户将我的 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 中实现诸如保存文件对话框之类的指导都将不胜感激。

【问题讨论】:

  • 功能需求究竟是什么?通过 HTTP 响应向最终用户提供 CSV 文件以供下载?还是让最终用户在网络服务器中选择 CSV 文件的保存位置(因此不会将其发送给最终用户)?似乎您正在混淆一些基本的 Web 开发概念。
  • @BalusC 不,我根本不想让他们保存在网络服务器中。我正在尝试为他们提供来自 HTTP 响应的 .CSV。我认为 Swing 行不通,但从未尝试过,我想我会试一试,但显然这不是正确的解决方案。

标签: java swing jsp servlets tomcat5.5


【解决方案1】:

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

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 标头负责 Save As 魔法。

另见:

【讨论】:

  • 感谢 BalusC,您多次提供了很大的帮助。欣赏它。
【解决方案2】:

您不能从 servlet 调用JFileChooser,因为 servlet 在服务器上运行,而不是在客户端上;您的所有 Java 代码都在服务器上执行。如果要将文件保存在服务器上,则需要已经知道要写入的路径。

如果要提示用户浏览器保存文件,请使用 content-disposition 标头:Uses of content-disposition in an HTTP response header

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 2015-01-21
相关资源
最近更新 更多