如何在 File 类中提供相对路径来上传任何文件? [复制]

2024-05-03

我正在上传一个文件,我想为其提供相对路径,因为该程序应该在 Linux 和 Windows 环境中运行。

这就是我用来上传的

realPath = getServletContext().getRealPath(/files);
destinationDir = new File(realPath);
if(!item.isFormField())
                {
                    File file = new File(destinationDir,item.getName());

                    item.write(file);
}

任何其他方式直接在此处提供相对路径

File file = new File(destinationDir,item.getName());

我想提供一个相对路径

切勿在网络应用程序中这样做。工作目录无法从代码内部控制。


因为该程序应该在 Linux 和 Windows 环境中运行。

只需使用"/path/to/uploaded/files"。它在两种环境中都同样有效。在 Windows 中,它只能与服务器运行所在的磁盘相同。

File file = new File("/path/to/uploaded/files", filename);
// ...

这就是我用来上传的

 realPath = getServletContext().getRealPath(/files);
 destinationDir = new File(realPath);

您不应将文件存储在网络内容中。当 WAR 未扩展时,此操作将会失败,即使扩展了,每当您重新部署 WAR 时,所有文件都会丢失。将它们存储在 WAR 之外的绝对位置,例如/path/to/uploaded/files正如之前所建议的。

也可以看看:

  • getResourceAsStream() 与 FileInputStream https://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream
  • 上传文件的最佳位置 https://stackoverflow.com/questions/4548190/best-location-for-uploading-file
  • 在 Java Web 应用程序中从应用程序服务器外部提供静态数据的最简单方法 https://stackoverflow.com/questions/1812244/simplest-way-to-serve-static-data-from-outside-the-application-server-in-a-java-w
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 File 类中提供相对路径来上传任何文件? [复制] 的相关文章

随机推荐