使用struts 2的文件上传需要先添加两个JAR文件,读者自己去查找。使用文件上传,在上传页面代码的<s:form>标签中使用其enctype属性,属性值为“multipart/form-data”,表示该编码方式会以二进制流的方式来处理表单数据。该编码方式还会把文件域中指定文件的内容封装到请求参数中,所以在文件上传时必须指定该属性。同时需要注意一点的是上传文件的默认大小限制是2MB,只要在配置文件“struts.properties”中修改参数“struts.multipart.maxSize”即可。部分代码如下:
JSP页面
<s:form action="upload" method="post" enctype="multipart/form-data">
action类页面
package org.user;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File upload;
private String uploadFileName;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String execute() throws Exception{
InputStream is = new FileInputStream(getUpload());//根据上传的文件得到输入流
OutputStream os = new FileOutputStream("d:\\upload\\"+uploadFileName);//指定输出流的地址
byte buffer[] = new byte[1024];
int count=0;
while((count = is.read(buffer))>0){
os.write(buffer,0,count);
}
os.close();
is.close();
return SUCCESS;
}
}