需用到两个包
commons-io-2.0.1.jar、commons-fileupload-1.3.jar
form表单必须加enctype="multipart/form-data"属性
<form action="Test/uploadAction" method="post" enctype="multipart/form-data">
<input type="file" name="upload"/>
<input type="file" name="upload"/>
<input type="file" name="upload"/>
<input type="submit" value="上传"/>
</form>
struts2核心配置文件
<!-- 配置信息 -->
<package name="Test" extends="struts-default" namespace="/Test">
<!-- 配置默认类 -->
<default-class-ref class="com.erp.test.TestAction"></default-class-ref>
<!-- 配置action -->
<action name="uploadAction" method="upload">
<result name="success">/upload.jsp</result>
</action>
</package>
后台实现上传模块
/*
* 这三个属性必须有
* */
//接收前台传来的文件
private File[] upload;
//接收前台处理后传来的文件类型
private String[] uploadContentType;
//接收前台处理后传来的文件名称
private String[] uploadFileName;
public String upload() throws Exception {
FileInputStream fileInput=null;
FileOutputStream fileOutput=null;
String path=ServletActionContext.getServletContext().getRealPath("")+"\\upload";
for(int i=0;i<upload.length;i++){
//用时间戳来作为保存后的文件名称
String newFileName=new SimpleDateFormat("yyyyMMddHHmmssSS").format(new Date());
//获取文件的后缀
String suffix=uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."));
//名称加后缀形成完整的文件名
newFileName+=suffix;
fileOutput=new FileOutputStream(new File(path+"\\"+newFileName));
fileInput=new FileInputStream(upload[i]);
byte[] b=new byte[1024];
int length;
while((length=fileInput.read(b))!=-1){
fileOutput.write(b,0,length);
}
}
fileOutput.close();
fileInput.close();
return "success";
}