搜尋
首頁後端開發php教程PHP關於AIP圖片上傳介面

PHP關於AIP圖片上傳介面

Mar 10, 2018 pm 01:37 PM
php上傳介面

PHP上傳的簡單案例:  

Html檔:



         

」樣式相關:

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

<input type="file" accept="image/*;capture=camera">直接调用相机
            <input type="file" accept="image/*" />调用相机 图片或者相册
 

#PHP檔:##

<?php $file = $_FILES[&#39;file&#39;];//得到传输的数据

//得到文件名称$name = $file[&#39;name&#39;];$type = strtolower(substr($name,strrpos($name,&#39;.&#39;)+1)); //得到文件类型,并且都转化成小写$allow_type = array(&#39;jpg&#39;,&#39;jpeg&#39;,&#39;gif&#39;,&#39;png&#39;); //定义允许上传的类型
//判断文件类型是否被允许上传if(!in_array($type, $allow_type)){    //如果不被允许,则直接停止程序运行
    return ;
}//判断是否是通过HTTP POST上传的if(!is_uploaded_file($file[&#39;tmp_name&#39;])){    //如果不是通过HTTP POST上传的
    return ;
}$upload_path = "./img/"; //上传文件的存放路径
//开始移动文件到相应的文件夹if(move_uploaded_file($file[&#39;tmp_name&#39;],$upload_path.$file[&#39;name&#39;])){    echo "Successfully!";
}else{    echo "Failed!";
}?>
 

#PHP檔:

##
    
      = 'maxSize'    =>    3145728,         
        'exts'       =>    ('jpg', 'gif', 'png', 'jpeg'),
        'rootPath'   =>    './Public/Uploads/info/',
        'savePath'   =>    '',                          
        'saveName'   =>    ('uniqid',''),
        'autoSub'    =>    ,                       
        'subName'    =>    ('date','Ymd'),  upload(['result'] = 1['imgurl'] = ''['msg'] = '' =  = ->upconfig['rootPath'] . ->upconfig['savePath'(!( = (, 0777, (!
                ['result'] = 0['msg'] = "创建保存图片的路径失败!"
             =  \Think\Upload(->

使用thinkphp上傳類別上傳的簡單案例:

(!
                ['result'] = 0['msg'] = ->
                 =  ->upconfig['rootPath'] . ['savepath'].['savename' = ('./', '/', ['result'] = 1['imgurl'] = (0 
         = ->upload(['attorney']);
    /**
     * 图片上传
     * @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;
    }
 

行動裝置App上傳圖片實例:API介面:

問題:APP上傳頭像,php作為API端該如何接收圖片訊息?

上傳部分的程式碼不是問題,主要是server端如何才能接收到APP端的圖片資訊。在B/S架構下,可以直接透過form表單設定enctype="multipart/form-data",$_FILES陣列中就有了圖片資訊。那麼在C/S模式中,也是如此嗎?

###### 答案1(見方式一)###: ###通常是採用二進位串流傳輸,客戶端傳的是二進位,伺服器端接收,然後file_put_contents寫入檔案就可以了。檔案名稱格式,檔案放哪裡,這些自己定義。 ############ 解答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;
    }

相关推荐:

相关推荐:

php 图片上传

图片和传真查看器 PHP 图片上传代码

PHP 图片上传代码_PHP教程

以上是PHP關於AIP圖片上傳介面的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何防止與會議有關的跨站點腳本(XSS)攻擊?您如何防止與會議有關的跨站點腳本(XSS)攻擊?Apr 23, 2025 am 12:16 AM

要保護應用免受與會話相關的XSS攻擊,需採取以下措施:1.設置HttpOnly和Secure標誌保護會話cookie。 2.對所有用戶輸入進行輸出編碼。 3.實施內容安全策略(CSP)限制腳本來源。通過這些策略,可以有效防護會話相關的XSS攻擊,確保用戶數據安全。

您如何優化PHP會話性能?您如何優化PHP會話性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显著提升应用在高并发环境下的效率。

什麼是session.gc_maxlifetime配置設置?什麼是session.gc_maxlifetime配置設置?Apr 23, 2025 am 12:10 AM

theSession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceisesneededeededeedeedeededto toavoidperformance andunununununexpectedLogOgouts.3)

您如何在PHP中配置會話名?您如何在PHP中配置會話名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函數配置會話名稱。具體步驟如下:1.使用session_name()函數設置會話名稱,例如session_name("my_session")。 2.在設置會話名稱後,調用session_start()啟動會話。配置會話名稱可以避免多應用間的會話數據衝突,並增強安全性,但需注意會話名稱的唯一性、安全性、長度和設置時機。

您應該多久再生一次會話ID?您應該多久再生一次會話ID?Apr 23, 2025 am 12:03 AM

會話ID應在登錄時、敏感操作前和每30分鐘定期重新生成。 1.登錄時重新生成會話ID可防會話固定攻擊。 2.敏感操作前重新生成提高安全性。 3.定期重新生成降低長期利用風險,但需權衡用戶體驗。

如何在PHP中設置會話cookie參數?如何在PHP中設置會話cookie參數?Apr 22, 2025 pm 05:33 PM

在PHP中設置會話cookie參數可以通過session_set_cookie_params()函數實現。 1)使用該函數設置參數,如過期時間、路徑、域名、安全標誌等;2)調用session_start()使參數生效;3)根據需求動態調整參數,如用戶登錄狀態;4)注意設置secure和httponly標誌以提升安全性。

在PHP中使用會議的主要目的是什麼?在PHP中使用會議的主要目的是什麼?Apr 22, 2025 pm 05:25 PM

在PHP中使用會話的主要目的是維護用戶在不同頁面之間的狀態。 1)會話通過session_start()函數啟動,創建唯一會話ID並存儲在用戶cookie中。 2)會話數據保存在服務器上,允許在不同請求間傳遞數據,如登錄狀態和購物車內容。

您如何在子域中分享會議?您如何在子域中分享會議?Apr 22, 2025 pm 05:21 PM

如何在子域名間共享會話?通過設置通用域名的會話cookie實現。 1.在服務器端設置會話cookie的域為.example.com。 2.選擇合適的會話存儲方式,如內存、數據庫或分佈式緩存。 3.通過cookie傳遞會話ID,服務器根據ID檢索和更新會話數據。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版