|
- <!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','api.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>
复制代码
- <?php
- //api.php
- header("Access-Control-Allow-Origin: *");//允许所有地址跨域请求
- if(empty($_FILES))die('上传为空文件');
- if($_FILES['pic']['error']!=0)die('文件上传出错');
- move_uploaded_file($_FILES['pic']['tmp_name'],'./'.$_FILES['pic']['name']);
- echo "{$_FILES['pic']['name']}文件上传成功!";
- ?>
复制代码 |
|