ajax與html5實現異步文件上傳
在之前的兩篇文章中,分別介紹了XMLHttpRequest對象和iframe僞異步文件上傳。在此就不再介紹介紹XMLHttpRequest對象了。之前說,單憑ajax是無法實現文件上傳的,原因是js不能操作主機的硬盤來獲取文件。但是隨着個瀏覽器商家逐步支持HTML5(實現了對ajax異步上傳文件的支持),ajax異步文件上傳變得可能。
ajax異步上傳思路
1.在html5中爲文件上傳的標籤<input type='file' name='' /> 的dom添加一個files文件列表對象,通過它我們可以在js中獲取文件的
信息和二進制資源。
2.在XMLHttpRequest的2版中添加了 FormData對象,來加載表單提交鍵值對。也可以用來加載文件資源。
3.ajax異步上傳文件,並且通過自身異步回調函數來實現後臺上傳文件的提示信息顯示和反饋。
前臺文件upload.html全部代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<title>ajax異步文件上傳</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript">
function createXHR()
{
var xhr=null;
if(window.XMLHttpRequest) //要是支持XMLHttpRequest的則採用XMLHttpRequest生成對象
xhr=new XMLHttpRequest();
else if(window.ActiveXobject)//要是支持win的ActiveXobject則採用ActiveXobject生成對象。
xhr=new ActiveXobject('Microsoft.XMLHTTP');
return xhr;
}
function ajax_upload()
{
var xhr=createXHR();
var formData=new FormData();
var file=document.getElementsByTagName('input')[0].files[0];//獲取文件列表中的第一個文件,html5中支持多個文件上傳
var info='文件名:'+file.name+' 文件類型:'+file.type+' 文件大小:'+file.size;//獲取文件的信息
var showInfo=document.getElementById('showinfo');
showInfo.innerHTML=info;
formData.append('pic',file);//加載圖片文件
xhr.open('POST','./move_file.php',true);
xhr.send(formData);
xhr.onreadystatechange=function(){
if( this.readyState==4 && this.status==200)
{
showInfo.innerHTML=showInfo.innerHTML+'<br />'+this.responseText;//將後臺提示信息放到指定div中顯示
}
}
}
</script>
</head>
<body>
<input type='file' name='pic' />
<input type='button' value='提交'onclick='ajax_upload();'/>
<div id='showinfo'></div>
</body>
後臺文件move_file.php全部代碼如下:
<?php
if(empty($_FILES))die('上傳爲空文件');
if($_FILES['pic']['error']!=0)die('文件上傳出錯');
move_uploaded_file($_FILES['pic']['tmp_name'],'./'.$_FILES['pic']['name']);
echo '文件上傳成功!';
?>
截圖如下: