1. 程式人生 > >TP 5 上傳圖片回顯 (AJAX非同步上傳圖片TP5)

TP 5 上傳圖片回顯 (AJAX非同步上傳圖片TP5)

直接上程式碼

PHP程式碼如下

/**
     * 上傳
     */
    public function upload_photo(){
        $file = $this->request->file('file');
        $uid = session('ydyl_weixin_user.id');
        // if(empty($uid)){
        //     return ['code'=>404,'msg'=>'使用者未登入'];
        // }
                if(!empty($file)){
                    // 移動到框架應用根目錄/public/uploads/ 目錄下
                    $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                    $error = $file->getError();
                    //驗證檔案字尾後大小
                    if(!empty($error)){
                        dump($error);exit;
                    }
                    if($info){
                        // 成功上傳後 獲取上傳資訊
                        // 輸出 jpg
                        $info->getExtension();
                        // 輸出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        $info->getSaveName();
                        // 輸出 42a79759f284b767dfcb2a0197904287.jpg
                        $photo = $info->getFilename();

                    }else{
                        // 上傳失敗獲取錯誤資訊
                        $file->getError();
                    }
                }else{
                    $photo = '';
                }
        if($photo !== ''){
            return ['code'=>1,'msg'=>'成功','photo'=>$photo];
        }else{
            return ['code'=>404,'msg'=>'失敗'];
        }
    }

HTML程式碼如下

<div class="upload-btn">
    <input type="file" name="pic1" id="pic" accept="image/gif,image/jpeg,image/x-png"/>
</div>
<script>
    //上傳圖片
    $('#pic').change(function(event) {
        var formData = new FormData();
        formData.append("file", $(this).get(0).files[0]);
        $.ajax({
            url:'http://www.juplus.cn/vdma/index/ydyl/upload_photo',
            type:'POST',
            data:formData,
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            success:function(data){
                console.log(data)
            }
        });
    });
</script>