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

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

问题描述

我正在上传一个文件,我想为其提供一个相对路径,因为该程序应该可以在 linux 和 windows env 中运行.

这是我用来上传的

realPath = getServletContext().getRealPath(/files);destinationDir = 新文件(真实路径);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 = 新文件(真实路径);

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

另见:

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天全站免登陆