如何设置“上下文路径”的路径使用Apache Common fileupload上传文件? [英] How to set the path to "context path" for uploaded files using Apache Common fileupload?

查看:347
本文介绍了如何设置“上下文路径”的路径使用Apache Common fileupload上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apache公共文件上载库和Netbeans 6.8 + Glassfish。我正在尝试将当前上载路径更改为位于servlet的当前上下文路径中,如下所示:
WEB-INF /上传

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

所以我写道:

File uploadedFile = new File("WEB-INF/upload/"+fileName);
session.setAttribute("path",uploadedFile.getAbsolutePath());
item.write(uploadedFile);

但我注意到图书馆将上传的文件保存到 glassfish文件夹,这是我打印上传文件的绝对路径时得到的结果:

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 :

C:\Program Files\sges-v3\glassfish\domains\domain1\WEB-INF\upload\xx.rar 

我的问题:


  • 如何强制公共文件上传将上传的文件保存在相对于当前的servlet路径,所以我不需要指定整个路径?这可能吗?

推荐答案

java.io.File 作用于本地磁盘文件系统,并且对其运行的上下文一无所知。当您传递相对Web路径 in。它将相对于当前工作目录,这取决于您启动环境的方式。你不想依赖它。

The java.io.File acts 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 path in. It would become relative to the current working directory which is dependent on how you started the environment. You don't want to be dependent on that.

你可以使用 要转换的ServletContext#getRealPath() 绝对本地磁盘文件系统路径的相对Web路径。

You can use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path.

String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(item.getName()));
// ...

这就是说,我希望你知道部署文件夹不是应该永久保存的上载文件的正确位置。重新部署Web应用程序时,一切都会丢失。另请参见如何将文件写入应用的资源/图片文件夹?

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?

这篇关于如何设置“上下文路径”的路径使用Apache Common fileupload上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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