Struts2实现文件上传
文件上传这个功能是很多网站都要有的,当然,Struts对文件上传也进了支持,可以说,使用Struts实现文件上传是非常简单的而且方便,下面来介绍一下。
首先,需要导入包commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar,后面的那个包是因为在下面的代码中会使用到它里面的一些方法,实际上也可以不加入,这些包都是可以在Struts的lib文件夹里面找到的.
然后就是写Action类了,这里需要接收文件(File类型),文件名,文件类型,文件名必须和表单里面的name属性名一致,学过servlet的都知道为什么,然后文件名的写法是文件名+FileName,然后文件类型名称的写法是文件名+ContentType,分别把他们设置成属性,就是分别为他们提供set和get方法。
接着需要把接受到的File文件转存到服务器的目录里,否则它就存放在Struts的临时目录里面,在Action执行完毕后会被删除。具体方法是使用servletContextgetRealPath方法获得项目的绝对路径,然后建立一个目录去存放这个上传的文件。
代码如下
-
- package com.bird.action;
-
- import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class FileUpload {
private File image;
private String imageFileName;
private String imageContentType;
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String execute(){
String path = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(path);
if(image != null){
File savefile = new File(new File(path),imageFileName);
if(!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
try {
FileUtils.copyFile(image , savefile);
} catch (IOException e) {
e.printStackTrace();
}
String[] t = imageContentType.split("/");
for(String s : t)
System.out.println(s);
}
return "success";
}
}
评论暂时关闭