struts2上传文件

struts2 上传文件
1、添加相应的jar包文件
commons-fileupload-1.3.1.jar
commons-io-2.2.jar


2、在form表单提交时设置为:enctype="multipart/form-data"
<form action="User/fileUpload.action" enctype="multipart/form-data" method="post">
		<input type="file" name="image">
		<input type="submit" value="上传文件">
</form> 

3、编写action类,
在action类中添加名称为上传表单字段的属性,添加对应的getter和setter方法;
如果想要获取文件名称,则可以添加属性:表单字段名称+FileName;
如果想要获取文件类型,则可以添加属性:文件类型:表单字段名称+ContentType。
e g:
	private File image;
	
	private String imageFileName;
	
	private String imageContentType;
	
	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;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}


4、操作文件上传
	public String addFile() throws IOException{
		String realPath = ServletActionContext.getServletContext().getRealPath("/images");
		if(image!=null){
			File dir = new File(realPath);
			if(!dir.exists()){
				dir.mkdirs();
			}
			FileUtils.copyFile(image, new File(dir,imageFileName));
			ActionContext.getContext().put("message", "文件传送成功!");
		}
		return "success";
	}


注意事项:
文件大小如果超过strut2中默认设置的最大大小时,文件会上传失败!解决方法,可以在struts.xml文件中设置上传文件大小的最大值,
<constant name="struts.multipart.maxSize" value="1024000000"/>

猜你喜欢

转载自catinthewater.iteye.com/blog/2310195