HTML5上传文件(不含进度条):XHR2+FILE+FormData

来源:互联网 发布:合肥seo网络推广 编辑:程序博客网 时间:2024/06/07 00:37
主要用到了三个方面的技术:
1.使用FILE的API获取待上传的文件对象,比如pic
var pic = document.getElementsByTagName("input")[0].files[0];
2.再使用FormData对象收集待发送的数据,参数其中之一是上面file获取到的对象pic
var fd = new FormData();
fd.append('pic',pic);
3.使用Ajax发送
var xhr = new XMLHttpRequest();
xhr.open('POST','fileup.php',true);
xhr.onreadystatechange = function(){
if(this.readyState ==4)
{
     document.getElementById('debug').innerHTML = this.responseText;
}

}

xhr.send(fd);




具体代码如下:

html5up.html如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"><head><title>fileAPI</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">function selfile(){//创建formData对象var fd = new FormData();//获取文件对象var pic = document.getElementsByTagName("input")[0].files[0];//把文件内容追加到表单数据里fd.append('pic',pic);var xhr = new XMLHttpRequest();xhr.open('POST','fileup.php',true);xhr.onreadystatechange = function(){if(this.readyState ==4){document.getElementById('debug').innerHTML = this.responseText;}}xhr.send(fd);}</script></head>    <body>    <input type="file" name="pic" onchange="selfile();" />    <div id="debug"></div>    </body></html>

用到的fileup.php如下:

<?php //print_r($_FILES);if(empty($_FILES)){exit ('no file');}if ($_FILES['pic']['error']!=0) {exit ('fail');}move_uploaded_file($_FILES['pic']['tmp_name'], 'upload/'.$_FILES['pic']['name']);echo 'ok';?>



0 0
原创粉丝点击