您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Ajax和PHP实现异步上传头像

2024/3/1 8:43:44发布20次查看
本文主要和大家分享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文件方法分享
html里怎样实现异步上传文件
php和ajax实现异步上传文件或图片代码分享
以上就是ajax和php实现异步上传头像的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product