日期:2014-05-16  浏览次数:20636 次

Ext ajax上传文件
上传文件的时候用ajax是不能实现的,因为文件传递安全性方面的考虑,ajax只能将文件名传递到后台,并不能将文件本身传递给后台,要在extjs实现文件上传必须采用在form中提交的方式,不过为了实现类似于ajax的用户体验,可以在配置项中添加fileUpload:true的方式,来实现异步提交,而不必出现页面跳转的方式。
<form id="upload">
<input type="file" id="image" name="image" />
</form>
采用Ext ajax提交form,并设置上传参数
Ext.Ajax.request({
		url : "upload.action",
		isUpload : true,
		form : "upload",
		
		success : function(response) {
			var jsonObj = Ext.JSON.decode(response.responseText);
			if (0 == jsonObj.result)
				alert("上传成功");
			else
				alert("上传失败");
		}
	});
后台使用的是struts2架构,只需要在对应的action类中定义同名的File参数获取文件信息
private File image;
public File getImage(){
    return image;
}
public void setImage(File image){
    this.image = image;
}
然后再对应的action处理方法中直接对image对象进行操作
public String upload() throws Exception{
		if (map != null && image.isFile()){
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(image));
			byte[] buff = new byte[(int) map.length()];
			bis.read(buff);
			result = 0;
			return SUCCESS;
		}
		else{
			result = 1;
			return ERROR;
		}
	}
操作结果以json形式返回给页面,result值为0表示成功,1表示失败。但是发现返回的json数据被封转多一个<pre>标签
<pre style="word-wrap: break-word; white-space; pre-wrap; ">{"result":0}</pre>
这是由于浏览器自动给返回结果封装成html,详细可看Ext说明文档http://docs.sencha.com/ext-js/4-0/#/api/Ext.form.Basic-method-hasUpload
解决方法是将返回结果的Content-type设置为text/html,这样浏览器就不会再加html标签,在struts2中需要在struts.xml中对返回结果增加Content-type说明。
<action name="upload" class="com.UploadAction" method="upload">
			<result name="success" type="json">
				<param name="contentType">text/html</param>
				<param name="includeProperties">
					result
				</param>
			</result>
			<result name="error" type="json">
				<param name="contentType">text/html</param>
				<param name="includeProperties">
					result
				</param>
			</result>
</action>