PHP 圖片上傳 (AIP圖片上傳接口)

 

PHP上傳的簡單案例:  php

Html文件:html

<html>

<form action="index.php" name="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" name="submit" value="上傳" />
</form>

</html>

 

樣式相關:thinkphp

  手機端,點擊上傳按鈕,彈出相機:json

    <input type="file" accept="image/*;capture=camera">直接調用相機
            <input type="file" accept="image/*" />調用相機 圖片或者相冊api

 

PHP文件:數組

<?php

$file = $_FILES['file'];//獲得傳輸的數據

//獲得文件名稱
$name = $file['name'];
$type = strtolower(substr($name,strrpos($name,'.')+1)); //獲得文件類型,而且都轉化成小寫
$allow_type = array('jpg','jpeg','gif','png'); //定義容許上傳的類型
//判斷文件類型是否被容許上傳
if(!in_array($type, $allow_type)){
    //若是不被容許,則直接中止程序運行
    return ;
}
//判斷是不是經過HTTP POST上傳的
if(!is_uploaded_file($file['tmp_name'])){
    //若是不是經過HTTP POST上傳的
    return ;
}
$upload_path = "./img/"; //上傳文件的存放路徑
//開始移動文件到相應的文件夾
if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){
    echo "Successfully!";
}else{
    echo "Failed!";
}

?>

 

使用thinkphp上傳類上傳的簡單案例:服務器

    // 上傳配置信息
    protected $upconfig = array(
        'maxSize'    =>    3145728,         // 3M
        'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
        'rootPath'   =>    './Public/Uploads/info/',
        'savePath'   =>    '',                          // => 上傳子目錄須要每一個函數本身去設置
        'saveName'   =>    array('uniqid',''),
        'autoSub'    =>    false,                       // 關閉子目錄保存
        'subName'    =>    array('date','Ymd'),
    );

    protected function upload($file) {

        $res['result'] = 1;
        $res['imgurl'] = '';
        $res['msg'] = '';

        do {

            $ret = true;
       //判斷路徑是否存在
$fullPath = $this->upconfig['rootPath'] . $this->upconfig['savePath']; if(!file_exists($fullPath)){
//若是不存在,建立文件夾
$ret = mkdir($fullPath, 0777, true); } if(!$ret) { // 上傳錯誤提示錯誤信息 $res['result'] = 0; $res['msg'] = "建立保存圖片的路徑失敗!"; break; } // 實例化上傳類 $upload = new \Think\Upload($this->upconfig); // 上傳單個文件 $info = $upload->uploadOne($file);

       // 上傳多個文件  
      
$info = $upload->upload();

if(!$info) { // 上傳錯誤提示錯誤信息 $res['result'] = 0; $res['msg'] = $upload->getError(); } else { // 上傳成功 獲取上傳文件信息 $imgurl = $this->upconfig['rootPath'] . $info['savepath'].$info['savename']; $imgurl = str_replace('./', '/', $imgurl); $res['result'] = 1; $res['imgurl'] = $imgurl; } } while(0); return $res; } // 保存上傳的文件 $res = $this->upload($_FILES['attorney']);

 

移動端App上傳圖片實例:API接口:架構

 

問題:APP上傳頭像,php做爲API端應該如何接收圖片信息?函數

上傳部分的代碼不是問題,主要是server端如何才能接收到APP端的圖片信息。在B/S架構下,能夠直接經過form表單設置enctype="multipart/form-data",$_FILES數組中就有了圖片信息。那麼在C/S模式中,也是如此嗎?

 解答1(見方式一)通常是採用二進制流傳輸,客戶端傳的是二進制,服務器端接收,而後file_put_contents寫入文件就能夠了。文件名格式,文件放哪裏,這些本身定義。post

 解答2(見方式二):Android或者IOS客戶端模擬一個HTTP的Post請求到服務器端,服務器端接收相應的Post請求後(經過$_FILES獲取圖片資源),返回響應信息給給客戶端。(這一種方式和獲取Html方式提交的方法同樣)

 

方式一:把圖片進行base64加密成字符串,進行傳輸

說明:IOS或者安卓端:經過把圖片進行base64編碼獲得字符串,傳給接口

        接口端:把接收的字符串進行base64解碼,再經過file_put_contents函數,上傳到指定的位置

    /**
     * 圖片上傳
     * @param $imginfo - 圖片的資源,數組類型。['圖片類型','圖片大小','圖片進行base64加密後的字符串']
     * @param $companyid - 公司id
     * @return mixed
     */
    public function uploadImage( $imginfo , $companyid ) {
        $image_type = strip_tags($imginfo[0]);  //圖片類型
        $image_size = intval($imginfo[1]);  //圖片大小
        $image_base64_content = strip_tags($imginfo[2]); //圖片進行base64編碼後的字符串

        $upload = new UploaderService();
        $upconfig = $upload->upconfig;

        if(($image_size > $upconfig['maxSize']) || ($image_size == 0)) {
            $array['status'] = 13;
            $array['comment'] = "圖片大小不符合要求!";
            return $array;
        }

        if(!in_array($image_type,$upconfig['exts'])) {
            $array['status'] = 14;
            $array['comment'] = "圖片格式不符合要求!";
            return $array;
        }

        // 設置附件上傳子目錄
        $savePath = 'bus/group/' . $companyid . '/';
        $upload->upconfig['savePath'] = $savePath;

        //圖片保存的名稱
        $new_imgname = uniqid().mt_rand(100,999).'.'.$image_type;

        //base64解碼後的圖片字符串
        $string_image_content = base64_decode($image_base64_content);

        // 保存上傳的文件
        $array = $upload->upload($string_image_content,$new_imgname);

        return $array;
    }
    // 上傳配置信息
    public $upconfig = array(
        'maxSize'    =>    3145728,         //3145728B(字節) = 3M
        'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
//        'rootPath'   =>    './Public/Uploads/info/',
        'rootPath'   =>    'https://www.eyuebus.com/Public/Uploads/info/',
    );

    /**
     * @param $string_image_content - 所要上傳圖片的字符串資源
     * @param $new_imgname - 圖片的名稱,如:57c14e197e2d1744.jpg
     * @return mixed
     */
    public function upload($string_image_content,$new_imgname) {

        $res['result'] = 1;
        $res['imgurl'] = '';
        $res['comment'] = '';

        do {
            $ret = true;
            $fullPath = $this->upconfig['rootPath'] . $this->upconfig['savePath'];
            if(!file_exists($fullPath)){
                $ret = mkdir($fullPath, 0777, true);
            }
            if(!$ret) {
                // 上傳錯誤提示錯誤信息
                $res['result'] = 12;
                $res['comment'] = "建立保存圖片的路徑失敗!";
                return $res;
                break;
            }

            //開始上傳
            if (file_put_contents($fullPath.$new_imgname, $string_image_content)){
                // 上傳成功 獲取上傳文件信息
                $res['result'] = 0;
                $res['comment'] = "上傳成功!";
                $res['imgname'] = $new_imgname;
            }else {
                // 上傳錯誤提示錯誤信息
                $res['result'] = 11;
                $res['comment'] = "上傳失敗!";
            }


        } while(0);

        return $res;
    }

 

 

 

方式二:Android或者IOS客戶端模擬一個HTTP的Post請求到服務器端,服務器端接收相應的Post請求後(經過$_FILES獲取圖片資源),返回響應信息給給客戶端。(這一種方式和獲取Html方式提交的方法同樣)

 

移動端須要請求一個URL,這個URL接收POST過去的數據,好比:http://www.apixxx.net/Home/Uploader/uploadPrepare

    public function uploadPrepare() {
        $array = array();

        $post_log = print_r($_POST, true);
        Log::record($post_log, 'DEBUG');
        $file_log = print_r($_FILES, true);
        Log::record($file_log, 'DEBUG');


        $token = $_POST['token'];

        $token_str          = jwt_decode($token);
$user_type          = $token_str['user_type'];


        // 設置附件上傳子目錄
        if($user_type == 1) {
            $savePath = 'travel/group/' . $user_companyid . '/';
        }elseif ($user_type == 2) {
            $savePath = 'bus/group/' . $user_companyid . '/';
        }elseif ($user_type == 3) {
            $savePath = 'driver/group/' . $user_companyid . '/';
        }else {
            $array['status'] = 3;
            $array['comment'] = '非法用戶!';
            return $array;
        }
        $this->upconfig['savePath'] = $savePath;


        // 保存上傳的文件(單張)
//        $res = $this->upload($_FILES['file']);

    
        // 保存上傳的文件(多張) 移動端的表單name=「xxx[]」,支持多張圖片
        $res = $this->upload();

        $array['status'] = $res['status'];
        $array['comment'] = $res['comment'];
        $array['responseParameters']['img_url'] = $res['img_url'];

        echo json_encode($array);
    }



    protected function upload() {

        $res['status'] = 1;
        $res['imgurl'] = '';
        $res['comment'] = '';

        do {

            $ret = true;
            $fullPath = $this->upconfig['rootPath'] . $this->upconfig['savePath'];
            if(!file_exists($fullPath)){
                $ret = mkdir($fullPath, 0777, true);
            }
            if(!$ret) {
                // 上傳錯誤提示錯誤信息
                $res['status'] = 1;
                $res['comment'] = "建立保存圖片的路徑失敗!";
                break;
            }

            // 實例化上傳類
            $upload = new \Think\Upload($this->upconfig);

//            // 上傳單個文件
//            $info = $upload->uploadOne($file);

            // 上傳多個文件
            $infos = $upload->upload();

            // 上傳的圖片數量
            $file_count = 0;
            foreach ($_FILES as $file_k => $file_v) {
                foreach ($file_v["size"] as $k => $v) {
                    if($v == 0) {
                        continue;
                    }
                    $file_count += 1;
                }
            }

            Log::record("info_log", 'DEBUG');
            $info_log = print_r($infos,true);
            Log::record($info_log, 'DEBUG');

            if(!$infos) {
                // 上傳錯誤提示錯誤信息
                $res['status'] = 2;
                $res['comment'] = $upload->getError();
            } else {
                // 獲取的上傳成功的圖片數量
                $info_count = 0;

                // 上傳成功 獲取上傳文件信息
                foreach($infos as $k => $v) {
                    $imgurl[$v['key']][] =  str_replace('./', '/', $this->upconfig['rootPath'] . $v['savepath'].$v['savename']);
                    $info_count += 1;
                }

                if($file_count != $info_count) {
                    $res['status'] = 1;
                    $res['comment'] = "上傳失敗!上傳的多張圖片,沒有所有上傳成功";
                }else {
                    $res['status'] = 0;
                    $res['comment'] = "上傳成功!";
                    $res['img_url'] = $imgurl;
                }
            }

        } while(0);

        return $res;
    }
相關文章
相關標籤/搜索