php+原生ajax实现图片文件上传功能实例
html+js 代码
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Html5 Ajax 上传文件</title> 5 <meta charset="utf-8"> 6 <script type="text/javascript"> 7 var xhr; 8 function createXMLHttpRequest() 9 { 10 if(window.ActiveXObject) 11 { 12 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 13 } 14 else if(window.XMLHttpRequest) 15 { 16 xhr = new XMLHttpRequest(); 17 } 18 } 19 function UpladFile() 20 { 21 var fileObj = document.getElementById("file").files[0]; 22 var FileController = 'upload.php'; 23 var form = new FormData(); 24 form.append("myfile", fileObj); 25 createXMLHttpRequest(); 26 xhr.onreadystatechange = handleStateChange; 27 xhr.open("post", FileController, true); 28 xhr.send(form); 29 } 30 function handleStateChange() 31 { 32 if(xhr.readyState == 4) 33 { 34 if (xhr.status == 200 || xhr.status == 0) 35 { 36 var result = xhr.responseText; 37 var json = eval("(" + result + ")"); 38 alert('图片链接:n'+json.file); 39 } 40 } 41 } 42 </script> 43 <style> 44 .txt{ height:28px; border:1px solid #cdcdcd; width:670px;} 45 .mybtn{ background-color:#FFF; line-height:14px;vertical-align:middle;border:1px solid #CDCDCD;height:30px; width:70px;} 46 .file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px } 47 </style> 48 </head> 49 <body> 50 <div class="form-group"> 51 <label class="control-label">图片</label> 52 <br/> 53 <input type='text' name='textfield' id='textfield' class='txt' /> 54 <span onclick="file.click()" class="mybtn">浏览...</span> 55 <input type="file" name="file" class="file" id="file" size="28" onchange="document.getElementById('textfield').value=this.value" /> 56 <span onclick="UpladFile()" class="mybtn">上传</span> 57 </div> 58 </body> 59 </html>
php代码
1 <?php 2 if(isset($_FILES["myfile"])) 3 { 4 $ret = array(); //用来保存图片上传之后的路径,文件名 5 $uploadDir = 'images'.DIRECTORY_SEPARATOR.date("Ymd").DIRECTORY_SEPARATOR; // DIRECTORY_SEPARATOR常量,解析后为"/"为了兼容不同系统之间路径写法的区别
6 $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.$uploadDir; //路径名,可以自己修改
7 file_exists($dir) || (mkdir($dir,0777,true) && chmod($dir,0777));
8 if(!is_array($_FILES["myfile"]["name"])) //single file
9 {
10 $fileName = time().uniqid().'.'.pathinfo($_FILES["myfile"]["name"])['extension'];
11 move_uploaded_file($_FILES["myfile"]["tmp_name"],$dir.$fileName); //移动到指定$dir 目录下,该目录不存在会自动创建,重命名上传的文件
12 $ret['file'] = DIRECTORY_SEPARATOR.$uploadDir.$fileName;
13 }
14 echo json_encode($ret);
15 }
16 ?>