<script type="text/javascript">
function creatXMLHttpRequest(){
var obj =null;
if(window.ActiveObject){
obj = new ActiveObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
window.onload=function(){
fileinfo=document.getElementById('myheads').files[0];
}
function uploaded(){
var xhr = creatXMLHttpRequest();
var fd = new FormData();
fd.append('myheads',fileinfo);
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
alert(xhr.responseText);
}
}
xhr.open('post','jsonupload.php');
xhr.send(fd);
}
</script>
<input type="file" id='myheads' name="myhead" value="wenjian"/>
<input type="button" value="上传" onclick="uploaded();"/>
</body>
上图为fileinfo的内容
立即显示被上传图片效果
window.onload=function(){
fileinfo=document.getElementById('myheads').files[0];
// console.log(fileinfo);
}
function uploaded(){
var xhr = creatXMLHttpRequest();
var fd = new FormData();
fd.append('myheads',fileinfo);
document.getElementById('img').src=window.URL.createObjectURL(fileinfo);
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
alert(xhr.responseText);
}
}
xhr.open('post','jsonupload.php');
xhr.send(fd);
}
总结:HTML5新特性FormData
可以通过:
fileinfo=document.getElementById('myheads').files[0];来捕获客户端上传文件的信息
将需要上传的文件信息载入到FormData对象内部
fd.append('finfo',fileinfo);
然后通过 window.URL.createObjectURL(fileinfo);文件的url地址信息,二进制编码存在
来源:oschina
链接:https://my.oschina.net/u/1788914/blog/283178