Java EE - 获取上传文件的真实路径的最佳方式? [英] Java EE - Best way to get real path to uploaded files?

查看:36
本文介绍了Java EE - 获取上传文件的真实路径的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有上传表单的 Web 应用程序,用户可以在其中上传文件.

I have a web application with an upload form where users can upload files.

我想将文件存储在文件"文件夹中.我希望这个文件夹直接放在 webapp-root 下.

I'd like to store the files a folder 'files'. And i'd like this folder to be placed directly under the webapp-root.

使用struts2,在我的uploadFileAction中,我可以很容易地设置这个路径 String uploadDir = ServletActionContext.getServletContext().getRealPath("/files")+ "/";

Using struts2, in my uploadFileAction, i can easily set this path with String uploadDir = ServletActionContext.getServletContext().getRealPath("/files")+ "/";

但是当我试图检索文件时,显然我试图访问文件的 bean 无权访问 getServletContext() 并因此在 getRealPath 上抛出一个空指针代码>

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.

有没有简单的方法来获取我的路径?我只想要我的 webapp 的根路径.不多不少...

Is there an easy way to get my paths? I just want the rootpath to my webapp. Nothing more nothing less...

推荐答案

我希望将此文件夹直接放在 webapp-root 下.

这行不通.每当您重新部署 web 应用程序甚至重新启动服务器时,所有这些文件都会丢失.这些文件不包含在原始 WAR 中.

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.

您需要将它们存储在 webapp 上下文之外的固定路径中.例如./var/webapp/uploads.您可以在属性文件或系统属性中配置此路径.

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.

这篇关于Java EE - 获取上传文件的真实路径的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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