`

struts2 多文件上传

 
阅读更多

多文件上传的处理步骤同多文件上传(加入jar文件、写form、写Action)

 

form表单:3个文件的名称要是一样的

 <form action="${pageContext.request.contextPath }/neu/upload_execute.action" enctype="multipart/form-data" method="post">
文件1: <input type="file" name="image">
文件2: <input type="file" name="image">
文件3: <input type="file" name="image">
 <input type="submit" value="上传">
 </form>

 

 

Action类:与单文件相比,只是将上传文件和上传文件名变成文件数组,在方法里使用循环进行创建文件

public class Upload {
	
	private File[] image;//此处要与jsp页面上的name的值一样,得到上传的文件

	private String[] imageFileName; //得到文件的名称  命名规则:字段名称+FileName
	
	private String imageContentType;//得到文件的类型   命名规则:字段名称+ContentType

	public String execute() throws Exception {
		
		//得到绝对路径
		String realpath = ServletActionContext.getServletContext().getRealPath("/images"); 
		System.out.println(realpath);
		//上传文件不为空
		if(image != null) {
			//文件夹
			File savedir = new File(realpath);
			//创建文件夹
			if(!savedir.exists()) {
				savedir.mkdirs();
			}
			for(int i = 0 ;i<image.length;i++) {
				File savefile = new File(savedir,imageFileName[i]);
				FileUtils.copyFile(image[i], savefile);
			}
			ActionContext.getContext().put("message", "上传成功");
		}
		return "success";
	}
	
	
	public File[] getImage() {
		return image;
	}

	public void setImage(File[] image) {
		this.image = image;
	}

	public String[] getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String[] imageFileName) {
		this.imageFileName = imageFileName;
	}
    
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics