本文主要和大家分享Ajax和PHP實現非同步上傳頭像執行個體,希望能協助到大家。
效果:
上傳頁面
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> </head> <body> 頭像:<img id="avatar" src="" height="35" width="35" alt=""><br /> 選擇檔案:<input type="file" id="file1" /><br /> <input type="button" id="upload" value="上傳" /> <span id="result"></span> <img src="5fd411e985d2c939b90e2dfb.gif" height="100" width="100" style="display:none" id="imgWait" /> <script src="jquery-1.11.2.min.js"></script> <script> $(function () { $("#upload").click(function () { $("#imgWait").show(); var formData = new FormData(); formData.append("myfile", document.getElementById("file1").files[0]); $.ajax({ url: "upload.php", type: "POST", dataType: 'json', data: formData, /** *必須false才會自動加上正確的Content-Type,否則會執行error步驟 */ contentType: false, /** * 必須false才會避開jQuery對 formdata 的預設處理,否則會報Uncaught TypeError: Illegal invocation * XMLHttpRequest會對 formdata 進行正確的處理 */ processData: false, success: function (data) { if(data.code == 200){ $('#avatar').attr('src',data.datas.filename); } $('#result').html(data.msg); $("#imgWait").hide(); setTimeout(function(){ $('#result').html(''); }, 1200); }, error: function () { alert("上傳失敗!"); $("#imgWait").hide(); } }); }); }); </script> </body></html>
後台代碼:
<?php $tmp_name = $_FILES['myfile']['tmp_name']; $current_time = date("Y-m-d H-i-s"); if(is_uploaded_file($tmp_name)){ $filename = './'.$current_time.'.jpg'; $return = move_uploaded_file($tmp_name,$filename); $return ? output('200','上傳成功!',['filename' => $filename]) : output('400','上傳失敗!'); }else{ output('555','非法檔案!'); } function output($code,$msg,$datas = array()){ $outputData = array( 'code' => $code, 'msg' => $msg, 'datas' => $datas ); exit(json_encode($outputData)); }