This article mainly shares with you examples of asynchronous uploading of avatars using Ajax and PHP. I hope it can help you.
Effect screenshot:
Upload page
<!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>
Backend code:
<?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)); }
Related recommendations:
angularjs uses $http to asynchronously upload Excel file method sharing
How to implement asynchronous file upload in html
php and ajax implement asynchronous uploading of files or image code sharing
The above is the detailed content of Ajax and PHP implement asynchronous uploading of avatars. For more information, please follow other related articles on the PHP Chinese website!