页面的代码:
<s:form action = "uploadPro" enctype="multipart/form-data">
<s:textfield name="title" label="文件上传"></s:textfield>
<s:file name="upload" label="选择文件"></s:file><br/>
<s:submit value="上传"></s:submit>
</s:form>
action中的代码:
package com.ultratest.oa.employee.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
//封装文件标题请求参数的属性
private String tiltle;
//封装上传文件域的属性
private File upload;
//封装上传文件类型的属性
private String uploadContentType;
//封装上传文件的文件名
private String uploadFileName;
//直接从struts.xml文件中配置的属性,也可以手工写
* <action name="uploadPro" class = "action.UploadAction">
* <parma name="savePath">/upload</param>
* 拦截器是限制上传类型和上传的大小
* <interceptor-ref name="fileUpload">
* <param name="allowTypes">image/png,image/gif,image/jpeg</param>
* <param name="maximumSize">2000</param>
* </interceptor-ref>
* </action>
private String savePath;
//提供相应的setter和getter
private String getSavePath()throws Exception{
return ServletActionContext.getServletContext().getRealPath("/WEB-INF"+savePath);
}
public String getTiltle() {
return tiltle;
}
public void setTiltle(String tiltle) {
this.tiltle = tiltle;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while((len=fis.read(buffer))>0){
fos.write(buffer,0,len);
}
return super.execute();
}
}