问题描述
我正在上传一个文件,为此我想提供一个相对路径,因为这个程序应该在linux和windows环境下工作。
这是我用来上传的内容
$ b $ pre $ realPath = getServletContext ().getRealPath(/文件);
destinationDir =新建文件(realPath);
if(!item.isFormField())
{
File file = new File(destinationDir,item.getName());
item.write(file);
}
在这里直接提供相对路径的任何其他方法
File file = new File(destinationDir,item.getName());
不要在webapp中这样做。工作目录不能从代码中控制。
$ b
只要使用/ path / to / uploaded / files 。它在两种环境中都同样有效。在Windows中,它将只与运行服务器的磁盘相同。
File file = new File(/ path / to / uploaded / files,filename);
// ...
您不应该将文件存储在webcontent中。当WAR没有被扩展时,这将会失败,甚至当它重新部署WAR的时候,所有的文件都会丢失。将它们存储在WAR之外的绝对位置,例如, / path / to / uploaded / files 就像之前建议的一样。
$ b b
I am uploading a file, for which I want to provide a relative path, because the program should work in both linux and windows env.
This is what I am using to upload
realPath = getServletContext().getRealPath(/files); destinationDir = new File(realPath); if(!item.isFormField()) { File file = new File(destinationDir,item.getName()); item.write(file); }
Any other means to directly provide relative path here
File file = new File(destinationDir,item.getName());
Never do that in a webapp. The working directory is not controllable from inside the code.
Just use "/path/to/uploaded/files". It works equally in both environments. In Windows it will only be the same disk as where the server runs.
File file = new File("/path/to/uploaded/files", filename); // ...
You should not store the files in the webcontent. This will fail when the WAR is not expanded and even when it is, all files will get lost whenever you redeploy the WAR. Store them outside the WAR in an absolute location, e.g. /path/to/uploaded/files as suggested before.
See also:
- getResourceAsStream() vs FileInputStream
- Best Location for Uploading file
- Simplest way to serve static data from outside the application server in a Java web application
这篇关于如何在File类中提供相对路径来上传任何文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!