Java EE - 获取上传文件的真实路径的最佳方法?
我有一个带有上传表单的网络应用程序,用户可以在其中上传文件。
我想将文件存储在“文件”文件夹中。我希望将此文件夹直接放置在 webapp-root 下。
使用struts2,在我的uploadFileAction中,我可以使用 String uploadDir = ServletActionContext.getServletContext().getRealPath("/files")+ "/"; 轻松设置此路径
但是当我尝试检索时文件,显然我尝试访问该文件的 bean 无法访问 getServletContext() ,因此会抛出一个空指针getRealPath
现在我想弄清楚我应该如何解决这个问题。我听说 spring 资源是可行的方法,但我找不到任何相关的例子。
有没有一种简单的方法可以获取我的路径?我只想要我的网络应用程序的根路径。不多不少...
I have a web application with an upload form where users can upload files.
I'd like to store the files a folder 'files'. And i'd like this folder to be placed directly under the webapp-root.
Using struts2, in my uploadFileAction, i can easily set this path with String uploadDir = ServletActionContext.getServletContext().getRealPath("/files")+ "/";
But when i'm trying to retrieve the files, apparently my bean which tries to access the file does not have access to getServletContext()
and thus throws a nullpointer on getRealPath
Now im trying to figure out how i should approach this. I've heard about spring resource is the way to go, but i cant find any relevant examples.
Is there an easy way to get my paths? I just want the rootpath to my webapp. Nothing more nothing less...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是行不通的。每当您重新部署 Web 应用程序甚至重新启动服务器时,所有这些文件都会丢失。也就是说,这些文件不包含在原始 WAR 中。
您需要将它们存储在 web 应用程序上下文之外的固定路径中。例如
/var/webapp/uploads
。您可以在属性文件中或系统属性中配置此路径。This isn't going to work. All those files will get lost whenever you redeploy the webapp or even when you restart the server. Those files are namely not contained as part of the original WAR.
You need to store them in a fixed path outside the webapp's context. E.g.
/var/webapp/uploads
. You can configure this path in a properties file or as a system property.我发现有几种方法可以完成此任务,无论您使用什么操作系统平台。我通常喜欢以某种与我的网络应用程序相关的方式存储我的文件。话虽这么说,最简单的方法是使用类文件作为参考来获取真实路径。我使用类似于下面的内容来存储我构建的一些 Web 应用程序的图像上传:
这可以使用 Web 应用程序中的静态实用程序类或任何与此相关的类来获取应用程序的真实路径来完成与操作系统无关。或者,在 servlet 中,如果我的应用程序库位于不同的区域,我还使用请求类来获取 Tomcat 位置,如下所示:
I've found that a few ways to accomplish this regardless of what OS platform you're using. I typically like to store my files in some way relative to my web application. This being said, the easiest way to do this is using your class file as a reference to get the real path. I use something similar to the following to store image uploads for a few web applications that I've built:
This can be done using a static utility class in your web app, or any class for that matter to obtain the real path of your application regardless of OS. Alternatively in a servlet I've also used the request class to get the Tomcat location if my appbase is in a different area, something like this: