import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class UploadRegFile extends ActionSupport implements RequestAware,SessionAware,ServletContextAware{
private Map<String, Object> request;
private Map<String, Object> session;
private ServletContext context;
// 用File数组来封装多个上传文件域对象
private File[] upload;
// 用String数组来封装多个上传文件名
private String[] uploadFileName;
// 用String数组来封装多个上传文件类型
private String[] uploadContentType;
/**
* 上传文件处理
* @return
* @throws Exception
*/
public String execute()throws Exception
{
int i=0;
String preFile=upload(upload[i], uploadFileName[i++]);
String bidFile=upload(upload[i], uploadFileName[i++]);
String durgCat=upload(upload[i], uploadFileName[i++]);
return SUCCESS;
}
/**
* 上传文件
* @param url
* @return
*/
private String upload(File src,String srcFileName)throws Exception
{
String targetDirectory = context.getRealPath("/upload");
String targetFileName = generateFileName(srcFileName);
File target = new File(targetDirectory, targetFileName);
String url="/upload/"+targetFileName;
FileUtils.copyFile(src, target);
return url;
}
/**
* 根据当前时间生成存储文件名
* @param fileName
* @return
*/
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
return formatDate + fileName;
}
/**
* @return the upload
*/
public File[] getUpload() {
return upload;
}
/**
* @param upload the upload to set
*/
public void setUpload(File[] upload) {
this.upload = upload;
}
/**
* @return the uploadFileName
*/
public String[] getUploadFileName() {
return uploadFileName;
}
/**
* @param uploadFileName the uploadFileName to set
*/
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
/**
* @return the uploadContentType
*/
public String[] getUploadContentType() {
return uploadContentType;
}
/**
* @param uploadContentType the uploadContentType to set
*/
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setServletContext(ServletContext ctx) {
this.context = ctx;
}
public Map<String, Object> getRequest() {
return request;
}
public void setRequest(Map<String, Object> request) {
this.request = request;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
}