public class ToUploadAction extends ActionSupport {
private List<File> fileUpload;
private List<String> fileUploadFileName;//文件的名称 如上传的文件是a.png 则fileuploadFileName值为"a.png"
private List<String> fileUploadContentType;//文件的类型 如上传的是png格式的图片,则fileuploadContentType值为"image/png"
/*
* 指定上传文件在服务器上的保存目录,需要在Action中为定义savePath变量并为其添加相应的setter和getter方法
* 便于Struts2将struts.xml中的<param name="savePath">uploads/</param>值赋给savePath属性
* <param>的作用就是为Action中的某些属性赋一个默认值,通常这样做的如配置路径、文件名之类的.... 传递参数
*/
private String savePath;//文件的保存位置 ,是在struts.xml中配置的
public String fileUpload() throws IOException{
int i = 0;
for(File f :this.getFileUpload()){
String absolutePath = ServletActionContext.getServletContext().getRealPath(""); // 获取项目根路径
//文件路径
String path = absolutePath + "/" + this.savePath + "/";
//创建路径,如果目录不存在,则创建
File file = new File(path);
if(!file.exists()) {
file.mkdirs();
}
//文件路径+文件名
path +=this.getFileUploadFileName().get(i);
//1.构建输入流
FileInputStream fis = new FileInputStream(f);
//2.构建输出流
FileOutputStream fos = new FileOutputStream(path);
//3.通过字节写入输出流
try {
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
fos.close();
}
i++;
}
return SUCCESS;
}
}
struts.xml配置
<struts>
<constant name="struts.devMode" value="true" />
<package name="fileUpload" extends="struts-default" namespace="/file">
<action name="fileUpload" class="com.deppon.file.ToUploadAction" method="fileUpload">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg
</param>
<param name="maximumSize">1024*1024</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<param name="savePath">uploads</param>
<result name="success">/success.jsp</result>
<result name="input">/fileUpload.jsp</result>
</action>
</package>
</struts>
fileUpload.jsp
<s:form action="./file/fileUpload.action" method ="POST" enctype ="multipart/form-data">
<s:file name ="fileUpload" label="图片"/>
<s:file name="fileUpload" label="图片"></s:file>
<s:file name="fileUpload" label="图片"></s:file>
<s:file name="fileUpload" label="图片"></s:file>
<s:submit value="上传" label="upload"/>
</s:form>
原文:http://www.cnblogs.com/fengyu9/p/3568647.html