如何在File类中提供相对路径来上传任何文件? [英] How to provide relative path in File class to upload any file?

查看:351
本文介绍了如何在File类中提供相对路径来上传任何文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上传一个文件,为此我想提供一个相对路径,因为这个程序应该在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()); 


解决方案


I想要提供一个相对路径


不要在webapp中这样做。工作目录不能从代码中控制。


$ b


因为程序应该在Linux和Windows环境下工作。


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

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








$ p $ lt; code> realPath = getServletContext()这是我用来上传的内容

.getRealPath(/文件);
destinationDir =新建文件(realPath);


您不应该将文件存储在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());

解决方案

I want to provide a relative path

Never do that in a webapp. The working directory is not controllable from inside the code.


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

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);
// ...


This is what i am using to upload

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

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:

这篇关于如何在File类中提供相对路径来上传任何文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆