本文主要和大家分享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)); }
相关推荐:
angularjs利用$http异步上传Excel文件方法分享
以上是Ajax和PHP实现异步上传头像的详细内容。更多信息请关注PHP中文网其他相关文章!