struts2 上传文件
package cn.temp.upload; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class Up01Action extends ActionSupport { // 1:声明File类型的属性,使用List<File> private File[] img; // 用于保存上传的文件的名称的 private String[] imgFileName; //用于保存上传文件的类型 private String[] imgContentType; //用于保存上传文件的大小 private Long[] size; public File[] getImg() { return img; } public void setImg(File[] img) { this.img = img; } public String[] getImgFileName() { return imgFileName; } public void setImgFileName(String[] imgFileName) { this.imgFileName = imgFileName; } public String[] getImgContentType() { return imgContentType; } public void setImgContentType(String[] imgContentType) { this.imgContentType = imgContentType; } public Long[] getSize() { return size; } public void setSize(Long[] size) { this.size = size; } @Override public String execute() throws Exception { size = new Long[img.length]; for (int i = 0; i < size.length; i++) { size[i] = img[i].length(); } String path = ServletActionContext.getServletContext().getRealPath("/files"); // 获取真实的保存的目录 for (int i = 0; i < img.length; i++) { FileUtils.copyFile(img[i], new File(path, imgFileName[i])); } return SUCCESS; } }
上传文件的前台页面
<form action="up02" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"><br> 说明:<input type="text" name="desc"><br> <input type="submit"> </form>
前台显示上传文件的信息页面
<p>文件上传成功</p> 文件名:${imgFileName}<br> 文件类型:${imgContentType}<br> 文件大小:${size}<br>
struts2 的 配置文件
<package name="example-upload" extends="struts-default"> <action name="up01" class="cn.temp.upload.Up01Action"> <result>/WEB-INF/temp/one.jsp</result> </action> </package>