首页 后端开发 php教程 Ajax和PHP实现异步上传头像

Ajax和PHP实现异步上传头像

Mar 10, 2018 am 11:38 AM
ajax php 头像

本文主要和大家分享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: &#39;json&#39;,
                        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){
                                $(&#39;#avatar&#39;).attr(&#39;src&#39;,data.datas.filename);
                            }
                            $(&#39;#result&#39;).html(data.msg);
                            $("#imgWait").hide();
                            setTimeout(function(){
                                $(&#39;#result&#39;).html(&#39;&#39;);
                            }, 1200);
                        },
                        error: function () {
                            alert("上传失败!");
                            $("#imgWait").hide();
                        }
                    });
                });
            });
        </script>
    </body>
</html>

后台代码:

<?php
    $tmp_name = $_FILES[&#39;myfile&#39;][&#39;tmp_name&#39;];
    $current_time = date("Y-m-d H-i-s");
    if(is_uploaded_file($tmp_name)){
        $filename = &#39;./&#39;.$current_time.&#39;.jpg&#39;;
        $return = move_uploaded_file($tmp_name,$filename);
        $return ? output(&#39;200&#39;,&#39;上传成功!&#39;,[&#39;filename&#39; => $filename]) : output(&#39;400&#39;,&#39;上传失败!&#39;);
    }else{
        output(&#39;555&#39;,&#39;非法文件!&#39;);
    }

    function output($code,$msg,$datas = array()){
        $outputData = array(
            &#39;code&#39; => $code,
            &#39;msg&#39; => $msg, 
            &#39;datas&#39; => $datas 
        );
        exit(json_encode($outputData));
    }

相关推荐:

angularjs利用$http异步上传Excel文件方法分享

html里怎样实现异步上传文件

php和ajax实现异步上传文件或图片代码分享

以上是Ajax和PHP实现异步上传头像的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

PHP教程
1594
276
Edge PDF查看器不起作用 Edge PDF查看器不起作用 Aug 07, 2025 pm 04:36 PM

testthepdfinanotherapptoderineiftheissueiswiththefileoredge.2.enablethebuilt inpdfviewerbyTurningOff“ eflblyopenpenpenpenpenpdffilesexternally”和“ downloadpdffiles” inedgesettings.3.clearbrowsingdatainclorwearbrowsingdataincludingcookiesandcachedcachedfileresteroresoreloresorelorsolesoresolesoresolvereresoreorsolvereresoreolversorelesoresolvererverenn

VS代码快捷方式专注于Explorer面板 VS代码快捷方式专注于Explorer面板 Aug 08, 2025 am 04:00 AM

VSCode中可通过快捷键快速切换面板与编辑区。要跳转至左侧资源管理器面板,使用Ctrl Shift E(Windows/Linux)或Cmd Shift E(Mac);返回编辑区可用Ctrl `或Esc或Ctrl 1~9。相比鼠标操作,键盘快捷键更高效且不打断编码节奏。其他技巧包括:Ctrl KCtrl E聚焦搜索框,F2重命名文件,Delete删除文件,Enter打开文件,方向键展开/收起文件夹。

以示例运行子过程 以示例运行子过程 Aug 06, 2025 am 09:05 AM

使用os/exec包运行子进程,通过exec.Command创建命令但不立即执行;2.使用.Output()运行命令并捕获stdout,若退出码非零则返回exec.ExitError;3.使用.Start()非阻塞启动进程,结合.StdoutPipe()实时流式输出;4.通过.StdinPipe()向进程输入数据,写入后需关闭管道并调用.Wait()等待结束;5.必须处理exec.ExitError以获取失败命令的退出码和stderr,避免僵尸进程。

修复:Windows Update无法安装 修复:Windows Update无法安装 Aug 08, 2025 pm 04:16 PM

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

如何使用PHP中的阵列 如何使用PHP中的阵列 Aug 20, 2025 pm 07:01 PM

phparrayshandledatAcollectionsefefityIndexedorassociativuctures; hearecreatedWithArray()或[],访问decessedviakeys,modifybyAssignment,iteratifybyAssign,iteratedwithforeach,andManipulationUsfunsionsFunctionsLikeCountLikeCountLikeCountLikeCountLikecount()

修复:以太网'身份不明网络” 修复:以太网'身份不明网络” Aug 12, 2025 pm 01:53 PM

Restartyourrouterandcomputertoresolvetemporaryglitches.2.RuntheNetworkTroubleshooterviathesystemtraytoautomaticallyfixcommonissues.3.RenewtheIPaddressusingCommandPromptasadministratorbyrunningipconfig/release,ipconfig/renew,netshwinsockreset,andnetsh

掌握foreach内部使用休息,继续和goto的流量控制 掌握foreach内部使用休息,继续和goto的流量控制 Aug 06, 2025 pm 02:14 PM

breakexitstheloopimmediatelyafterfindingatarget,idealforstoppingatthefirstmatch.2.continueskipsthecurrentiteration,usefulforfilteringitemsliketemporaryfiles.3.gotojumpstoalabeledstatement,acceptableinrarecaseslikecleanuporerrorhandlingbutshouldbeused

比较和对比PHP特征,抽象类别和界面与实际用例。 比较和对比PHP特征,抽象类别和界面与实际用例。 Aug 11, 2025 pm 11:17 PM

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

See all articles