第一步:编写jsp页面
<td> <input type="text" name="address" id="ftext" readonly > <input type="button" onclick="felement.click()" value="上传" > <input type="file"" name="upload" id="felement" style="opacity: 0" onchange="ftext.value=this.value; "> </td>
第二步:配置struts.xml
<package name="action" extends="struts-default"> <action name="InsertPic" class="MyPicAction.AddMyPicAction"> <result name="input">/error.jsp</result> <result name="success">/Succeed.jsp</result> </action> </package>
第三步:编写action
package MyPicAction;
import java.io.File;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import pojo.Mypic;
import UserDao.DBManagement;
import com.opensymphony.xwork2.ActionSupport;
public class AddMyPicAction extends ActionSupport implements
ServletContextAware{//实现这个接口,对context进行传值
private ServletContext context;
private String picName;//表单传递的值
private String style;//表单传递的值
private File upload;// 实际上传文件
private String uploadContentType; // 文件的内容类型
private String uploadFileName; // 上传文件名
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 String getPicName() {
return picName;
}
public void setPicName(String picName) {
this.picName = picName;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
@Override
public String execute() throws Exception {
String targetDirectory="";
String filename = uploadFileName;
try {
targetDirectory = context.getRealPath("/upload");
String targetFileName = uploadFileName;
File target = new File(targetDirectory, targetFileName);
FileUtils.copyFile(upload, target);
setUploadFileName(target.getPath());//保存文件的存放路径
} catch (Exception e) {
addActionError(e.getMessage());
return INPUT;
}
System.out.println(uploadFileName);
DBManagement db = new DBManagement();
Mypic mypic = new Mypic();
mypic.setAddress("./upload/"+filename);
mypic.setName(picName);
mypic.setFlag(style);
if(db.InsertPic(mypic))
{
return SUCCESS;
}
else
{
return ERROR;
}
}
public void setServletContext(ServletContext context) {
this.context = context;
}
}
此时文件已经上传至./upload/***中了