Struts2 文件上传与接收页面参数

文件上传是网站中经常使用的。

文件上传的API也比较多,本人之前用过JSP smart upload的API,最有名的文件上传的API当属apache

commons-fileupload,struts2中文件上传就更简单了,下面是一个Struts2简单的文件上传的例子。

action类

 

private String username;
	private String password;
	private String secret;
	//上传的文件对象
	private File uploadFile;
	//文件名称
	private String uploadFileFileName;
	//文件类型
	private String uploadFileContentType;
	
	//性别
	private String sex;
	//爱好
	private String[] hobby;
	//出生国家
	private String country;
	//国籍
	private String[] guoji;
	private String desc;
	
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String submit(){	
		List hobbys = new ArrayList();
		Collections.addAll(hobbys, hobby);
		
		List guojis = new ArrayList();
		Collections.addAll(guojis, guoji);
		System.out.println("username="+username+",password="+password+",secret="+secret+",file="+uploadFile+",sex="+sex+",hobby="+hobbys+",country="+country+",guoji="+guojis+",desc="+desc);
		System.out.println("filename="+uploadFileFileName+",content type="+uploadFileContentType+",length="+uploadFile.length());
		return SUCCESS;
	}

        setter and getter method

 

struts.xml,action配置没有什么特殊之处,文件上传的action要使用默认的拦截器栈,默认的拦截器栈

中有文件上传的拦截器

 




        
            /hello.jsp
        
    

JSP代码

 

username:
password:
file:
sex:M  F
hobby:Music   Art  Dance
birthday country:
guoji:
desc:

 

 文件上传页面需要注意的一点是表单form要设置为enctype="multipart/form-data",默认

enctype="application/x-www-form-urlencoded"

Struts2之所以能够如此简单地进行文件上传,是因为有文件上传拦截器FileUploadInterceptor,action

中的属性uploadFileFileName和uploadFileContentType,是文件上传拦截器自动完成的赋值。格式为File对象的名称+FileName 和 File对象的名称+ContentType。

此外还可以看到表单中的参数和action属性的映射,单选按钮对应String,多选按钮对应String[],单选

的下拉列表对应String,多选的下拉列表对应String[]等。

 

 

你可能感兴趣的:(Struts)