Struts2上传文件路径问题小解
得益于Struts2的包装,使得上传文件变得十分简单,可是对于上传的文件究竟保存到哪里去了?还有为什么可能会抛出FileNotFoundException呢?我试了几次,大概领悟到了什么,记录下来,给新手看看。本人才疏学浅,望各位不吝指教。
至于Struts2的怎样实现上传,这个网上着实一大把,由于不是本篇的核心,所以,不赘述。
1、不指定目录情况下,文件会被上传到Tomcat的Bin目录。
即我们在创建FileOutputStream时候如下:
FileOutputStream fos = new FileOutputStream(getPhotofileFileName());
文件会被上传到apache-tomcat\bin目录,为什么会上传到这里,十分不解,暂且记住。
2、实现上传文件存储在相对目录,可以考虑实现ServletContextAware接口。
public class UploadAction extends BaseAction implements ServletContextAware {
...
private ServletContext context;
public void setServletContext(ServletContext context) {
this.context = context;
}
...
public String execute() throws FileNotFoundException, IOException {
...
FileOutputStream fos = new FileOutputStream(context.getRealPath(getPhotofileFileName()));
...
}
上面的代码实现了ServletContextAware接口,添加了一个ServletContext属性,在生成存储路径的时候,调用ServletContext.getRealPath(path)可以获得运行环境(即Application文件夹)下的path目录,如,我的Application名称叫Webgallery,调用ServletContext.getRealPath("images")就可以定位到Webgallery/images。再在这个基础上,定为路径,就很容易实现上传文件相对定位存储了。
3、上传文件抛出FileNotFoundException
抛出这个异常的原因可能是上传文件指定的目录不存在,可以再确认一下对应目录是否正确,是否真实存在。下面是官方关于FileNotFoundException的描述:
Signals that an attempt to open the file denoted by a specified pathname has failed.
This exception will be thrown by the FileInputStream
,
FileOutputStream
,
and RandomAccessFile
constructors when a file with the specified pathname does not exist. It will
also be thrown by these constructors if the file does exist but for some reason
is inaccessible, for example when an attempt is made to open a read-only file
for writing.
可能抛出FileNotFoundException异常的FileOutputStream类部分描述:
If the file exists but is a directory rather than a regular file, does not exist
but cannot be created, or cannot be opened for any other reason then a
FileNotFoundException
is thrown.
4、上传文件到绝对路径
这个功能可能不常用,但是我们的确可以很easy的实现:
FileOutputStream fos = new FileOutputStream("D:\\"+getPhotofileFileName());
指定绝对路径即可。