Ajax文件上传
一般提到ajax,我们一般会有两种方式,比较广为使用的是XHttpRequest,但是由于我们在客户端无法直接访问本地文件,因此使用xhttprequest进行文件上传的方式似乎不可行,那么不妨看看另外一种ajax方式,即利用frame。
前置知识
form的target属性
值 | 描述 |
_blank | 在新窗口中打开 |
_self | 默认。在相同的框架中打开 |
_parent | 在父框架集中打开 |
_top | 在整个窗口中打开 |
framename | 在指定的框架中打开 |
在这里,我们设置了form的target属性后,表单提交后返回的内容只会刷新指定的框架而不会影响当前页面,这样我们就实现了无刷新即ajax上传。
基本原理
html结构式这样的:
1
2
3
4
5
|
< form action = "/upload" method = "post" target = "iframe1" > < input type = "file" /> < input type = "submit" value = "上传" /> </ form > < iframe name = "iframe1" src = "javascript:false;" ></ iframe > |
这样我们就完成了一个基本的文件上传了,so easy吧。。
然后我们只需要处理iframe的onload的事件,获取上传信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
iframe.onload = function (){ var doc = iframe.contentDocument; if (doc.readyState && doc.readyState !== 'complete' ){ return ; } if (doc.body && doc.body.innerHtml == 'false' ){ return ; } if (doc.XMLDocument) { response = doc.XMLDocument; } else if (doc.body){ response = doc.body.innerHtml; } //do anything you want } |
这样一个简单的上传文件就ok了。
坑
ie下无法识别application/json格式,因此服务端返回时不能直接返回json格式,需要转化成string在客户端在解析。ok