java 如何使用 Apache Common fileupload 将上传文件的路径设置为“上下文路径”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2901961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the path to "context path" for uploaded files using Apache Common fileupload?
提问by Abdullah
I'm using Apache common fileupload library with Netbeans 6.8 + Glassfish.I'm trying to change the current upload path to be in the current context path of the servlet , something like this: WEB-INF/upload
我正在使用带有 Netbeans 6.8 + Glassfish 的 Apache 通用文件上传库。我试图将当前上传路径更改为 servlet 的当前上下文路径,如下所示:WEB-INF/upload
so I wrote :
所以我写道:
File uploadedFile = new File("WEB-INF/upload/"+fileName);
session.setAttribute("path",uploadedFile.getAbsolutePath());
item.write(uploadedFile);
but I noticed that the library saves the uploaded files into glassfish folder, here what I get when I print the absolute path of the uploaded file :
但我注意到库将上传的文件保存到glassfish 文件夹中,这是我打印上传文件的绝对路径时得到的:
C:\Program Files\sges-v3\glassfish\domains\domain1\WEB-INF\upload\xx.rar
My Question :
我的问题 :
- How can I force the common fileupload to save the uploaded file in a path relative to the current servlet path , so I don't need to specify the whole path ? is this possible ?
- 如何强制公共文件上传将上传的文件保存在相对于当前 servlet 路径的路径中,这样我就不需要指定整个路径?这可能吗 ?
回答by BalusC
The java.io.Fileacts on the local disk file system and knows absolutely nothing about the context it is running in. You should not expect it to find the "right" location when you pass a relative web pathin. It would become relative to the current working directorywhich is dependent on how you started the environment. You don't want to be dependent on that.
该java.io.File作用于本地磁盘文件系统上,并知道绝对没有关于它的运行环境。你不应该指望它来寻找“正确”的位置,当你传递一个相对的网络路径中。这将成为相对于当前的工作目录这取决于您如何启动环境。你不想依赖它。
You can use ServletContext#getRealPath()to convert a relative web path to an absolute local disk file system path.
您可以使用ServletContext#getRealPath()将相对 Web 路径转换为绝对本地磁盘文件系统路径。
String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(item.getName()));
// ...
That said, I hope that you're aware that the deploy folder isn't the right location for uploaded files which are supposed to be saved permanently. Everything will get lost when you redeploy the webapp. See also How to write a file to resource/images folder of the app?
也就是说,我希望您知道部署文件夹不是应该永久保存的上传文件的正确位置。当您重新部署 web 应用程序时,一切都会丢失。另请参阅如何将文件写入应用程序的资源/图像文件夹?

