java - 如何在 File 类中提供相对路径来上传任何文件?

标签 java servlets file-upload

<分区>

我正在上传一个文件,我想为其提供一个相对路径,因为该程序应该在 linux 和 windows env 中工作。

这是我用来上传的

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());

最佳答案

I want to provide a relative path

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


because the program should work in both linux and windows env.

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

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

This is what i am using to upload

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

您不应将文件存储在网络内容中。当 WAR 未展开时,这将失败,即使展开,只要您重新部署 WAR,所有文件都会丢失。将它们存储在 WAR 之外的绝对位置,例如/path/to/uploaded/files 如前所述。

另见:

关于java - 如何在 File 类中提供相对路径来上传任何文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6059453/

相关文章:

Java Selenium Chromedriver加载Cookie但不使用它们

java - 正则表达式仅匹配字符串中的一个字符序列

java - 通过 JMX 查看 Ehcache 数据

java - Atmosphere + Spring + Autowiring 问题

php - 检查ajax文件上传中的错误

javascript - NodeJS - multer - 根据请求属性更改文件名

java - 亚马逊网络服务 - API 网关

java - HttpServletRequest.getParameterValues() 中的值排序

java - 每当上下文加载(tomcat 启动)时,如何在 java web 应用程序中自动运行 servlet/action

asp.net-core - .Net Core 仅在上传文件时被 CORS 策略错误阻止