大家都知道struts2对文件上传做了很好的封装,使文件上传不再那么恐怖。这里面struts2的文件上传主要依赖的是org.apache.struts2.interceptor.FileUploadInterceptor这个拦截器
关于这个拦截器我不想做过多的研究,这里主要讨论的是该拦截器里面定义的几个关于文件上传的重要属性。
protected Long maximumSize; //允许上传单个文件的大小单位为字节
protected String allowedTypes; //允许上传的文件类型详见tomcat中web.xml文件
protected Set allowedTypesSet;
//允许上传的文件类型Set集合详见tomcat中web.xml文件
allowedTypes与allowedTypesSet属性如有多个值之间用逗号隔开
以上的属性主要配置在struts.xml中对应文件上传Action的拦截器中
示列:
//设置允许上传单个文件的大小单位为字节
102400
//允许上传的文件类型详见tomcat中web.xml文件
image/jpeg
注意:要使用文件上传功能我们必须显实的在对应文件上传的Action中指定
示列代码:
Action中的示列代码
publicclass FileUploadAction extends ActionSupport {
private File file;
private String fileContentType;
private String fileFileName;
private String memo;
@Override
public String execute() throws Exception {
String path=ServletActionContext.getRequest().getRealPath("/upload");
if(file==null)
{
this.addFieldError("file", "文件不能为空,请选择");
returnINPUT;
}else
{
InputStream is=new FileInputStream(this.getFile());
OutputStream os=new FileOutputStream(new File(path,this.getFileFileName()));
byte[] buf=newbyte[1024];
int length=0;
while((length=is.read(buf))>0)
{
os.write(buf, 0, length);
}
is.close();
os.close();
}
returnSUCCESS;
}
public File getFile() {
returnfile;
}
publicvoid setFile(File file) {
this.file = file;
}
public String getFileContentType() {
returnfileContentType;
}
public String getFileFileName() {
returnfileFileName;
}
public String getMemo() {
returnmemo;
}
publicvoid setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
publicvoid setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
publicvoid setMemo(String memo) {
this.memo = memo;
}
}
jsp中的示列代码
struts.xml中的示列代码
102400
application/msword
注意:
a) 设置文件上传属性在Action中对应的类型的java.io.File;
b) 设置文件上传表单的enctype="multipart/form-data" method="post"
private File file;
private String fileContentType;
private String fileFileName;
c) 红色标注的与文件上传表单中文件上传属性的name一致
d) 蓝色的为固定写法
e) 对应Action中拦截器的配置
&n