<input type="file" class="upload" name="upload"/>
package com.baitw.struts.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 UploadImage extends ActionSupport {
private String title;
private File upload;
private String uploadContextType;
private String uploadFileName;
private String savePath;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContextType() {
return uploadContextType;
}
public void setUploadContextType(String uploadContextType) {
this.uploadContextType = uploadContextType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
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 length=0;
while((length=fis.read(buffer))>0){
fos.write(buffer,0,length);
}
return "upload_success";
}
}
<!-- 上传图片 -->
<action name="uploadImage" class="uploadImage">
<!-- 动态设置文件保存路径的属性值 -->
<param name="savePath">/uploadImages</param>
<result name="upload_success">/succ.jsp</result>
<result name="input">/view/globalError.jsp</result>
</action>
<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>上传成功</title>
</head>
<body>
<img src="<s:property value="'uploadImages/'+uploadFileName"/>"/><br>
</body>
</html>