개발 꿀팁/PHP

Ajax+PHP 비동기식 프로필 사진 업로드 사례

Jammie 2022. 7. 29. 12:42
반응형

효과 캡처:

페이지 업로드

<!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,
                        /**
                        *올바른 Content-Type은 false가 되어야 자동으로 추가됩니다,그렇지 않으면 error 단계를 수행합니다
                        */
                        contentType: false,
                        /**
                        * formdata에 대한 jQuery의 기본 처리를 피하려면 false가 필요합니다,그렇지 않으면 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));
    }

 

반응형