天天看點

PHP 寫 APP 上傳圖檔接口

//上傳頭像
    public function upHeadImage(){
        $base64_img = trim($_POST['img']);//img前台将圖檔轉為base64  post  過來
        $userID = $_POST['uid'];
        // echo  $base64_img;
        $up_dir = './uploads/images/userphoto/';//存放在目前目錄的upload檔案夾下
        //判斷是否存在此檔案夾
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777);//進行檔案建立
        }
        //比對出圖檔的格式
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.date('YmdHis_').'.'.$type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    //圖檔路徑
                    $img_path = str_replace('../../..', '', $new_file);
                    $sql = "UPDATE userInfo set url='{$img_path}' where userID='{$userID}'";
                    $res = $this->db->query($sql);
                    $cnt = $res->rowCount();
                    //根據不同的傳回結果,對其進行相應的響應
                    if ($cnt >= 1) {
                        Response::json(203,"頭像上傳成功",$img_path);
                        exit;
                    } elseif ($res == false) {
                        Response::json(407,"頭像上傳失敗",$res);
                    } else {
                        Response::json(500,"未知錯誤",$res);
                    }
                }else{
                           Response::json(407,"頭像上傳失敗");
                }
            }else{
                    //檔案類型錯誤
                    Response::json(404,"頭像上傳類型錯誤");
            }
        }else{
            //檔案錯誤
            Response::json(404,"頭像檔案錯誤");
        }

    }
           

問題:

前台将圖檔轉為base64  POST  過來,在服務端輸出接收的POST資料 與圖檔轉碼後的資料對比 結果發現 圖檔轉成base64後有“+”, 但是接收的資料中“+”變成了“ ”;

解決方法:

1.     //前台先對base64格式的圖檔進行編碼,再進行解碼,傳到背景的資料必須是解碼後的資料

       //  var urlEncode = encodeURIComponent(imgData);

        var decode = decodeURIComponent(imgData);

2.    可在PHP接口出對POST過來的base64進行處理,将“ ”替換為“+”

        $base64_img = str_replace(" ","+",$base64_img);

//指定允許其他域名通路

header('Access-Control-Allow-Origin:*');

//設定時區

date_default_timezone_set('Asia/shanghai');

繼續閱讀