如何在基于 servlet 的 Web 应用程序中临时保存生成的文件

How to save generated file temporarily in servlet based web application

我正在尝试生成 XML 文件并将其保存在 /WEB-INF/pages/ 中。

下面是我使用相对路径的代码:

File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));

当 运行 作为本地计算机上的应用程序时,它工作正常 (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).

但是在服务器机器上部署和 运行 时,抛出以下异常:

javax.xml.transform.TransformerException: java.io.FileNotFoundException C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml

我也试过 getServletContext().getRealPath(),但它在我的服务器上返回 null。有人可以帮忙吗?

只需使用

File relpath = new File(".\pages\");

默认情况下,应用程序光标位于 web-inf 文件夹中。

从不 在 Java EE 网络应用程序中使用相对本地磁盘文件系统路径,例如 new File("filename.xml")。有关深入说明,另请参阅 getResourceAsStream() vs FileInputStream.

从不 使用getRealPath() 来获取写入文件的位置。如需深入解释,另请参阅 What does servletcontext.getRealPath("/") mean and when should I use it.

从不 将文件写入部署文件夹。如需深入解释,另请参阅 Recommended way to save uploaded files in a servlet application.

始终将它们写入预定义绝对路径上的外部文件夹。

  • 硬编码:

      File folder = new File("/absolute/path/to/web/files");
      File result = new File(folder, "filename.xml");
      // ...
    
  • 或在one of many ways中配置:

      File folder = new File(System.getProperty("xml.location"));
      File result = new File(folder, "filename.xml");
      // ...
    
  • 或利用container-managed temp folder:

      File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
      File result = new File(folder, "filename.xml");
      // ...
    
  • 或利用OS-managed temp folder:

      File result = File.createTempFile("filename-", ".xml");
      // ...
    

替代方法是使用(嵌入式)数据库或 CDN 主机(例如 S3)。

另请参阅:

  • Recommended way to save uploaded files in a servlet application
  • Where to place and how to read configuration resource files in servlet based application?
  • Store PDF for a limited time on app server and make it available for download
  • What does servletcontext.getRealPath("/") mean and when should I use it
  • getResourceAsStream() vs FileInputStream