我正在上传一个文件,我想为其提供一个相对路径,因为该程序应该在 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
如前所述。
另见: