首先我们需要一个简单的上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="uploadAction.action" method="post" enctype="multipart/form-data" >
<input type="file" name="upload" maxlength="1024*2">
<input type="submit" value="upload">
</form>
</body>
</html>
创建一个名称为com.action的包,然后在包下面创建FileUploadAction.java文件,实现struts的单文件上传
package com.test.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
封装属性 获取前台的文件,文件名和属性 使用get和set方法
private File upload;
private String uploadFileName;
private String uploadContentType;
public String upload(){
//获取上传路径
String realPath=ServletActionContext.getServletContext().getRealPath("/upload");
File savePath=new File(realPath);
if(!savePath.exists()){
savePath.mkdir();
}
File uploadFile=new File(realPath,uploadFileName);
try {
FileUtils.copyFile(upload, uploadFile);
} catch (IOException e) {
}
return SUCCESS;
}
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 getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
}