PHP之OSS

chajinglong發表於2017-02-16

首先PHP要引入OSS核心類庫



授權訪問-讀
授權訪問-寫

裡邊包含Config.php,OssClient.php,readAuth.php,writeAuth.php,writeConfig.php等配置檔案
config.php
<?php namespace Utils\OSS;
/**
 *
 * @description 授權訪問-讀
 */
final class Config
{
    const OSS_ACCESS_ID = '****************';
    const OSS_ACCESS_KEY = '**********************';
    //北京節點外網地址:oss-cn-beijing.aliyuncs.com
    //北京節點內網地址:oss-cn-beijing-internal.aliyuncs.com
//    const OSS_ENDPOINT = 'oss-cn-beijing.aliyuncs.com';
//    const OSS_TEST_BUCKET = 'dapeng-video';

    const OSS_ENDPOINT = 'oss-cn-hangzhou.aliyuncs.com';
    const OSS_TEST_BUCKET = 'zhijin-vod';

    const OSS_LIVE_ENDPOINT = 'oss-cn-hangzhou.aliyuncs.com';
    const OSS_LIVE_BUCKET = 'zhijin-live';
}

OssClient.php,readAuth.php,writeAuth.php 裡邊包含一些關於oss的大量資訊,bucket(桶,工具)也就是儲存的工具、以及一些拿到getBucketName()方法、avatar

上傳頭像到oss
 public function avatar($object = null,$file = null)
    {
        $obj = self::getOssClient();
        $obj->uploadFile(self::bucket,$object,$file);

        return true;
    }

講圖片的許可權設定成public-read
   public function avatarAcl($object = null)
    {
        $obj = self::getOssClient();
        $obj->putObjectAcl(self::bucket,$object,"public-read");

        return true;
    }


writeConfig.php
授權訪問-寫
<?php namespace Utils\OSS;
/**
 * Created by PhpStorm.
 * Date: 16-9-27
 * Time: 下午7:23
 * @description 授權訪問-寫
 */
final class writeConfig
{
    const OSS_ACCESS_ID     = '***********';
    const OSS_ACCESS_KEY    = '**************';
//    const OSS_INTERNAL_HOST = 'http://dapeng-video.vpc100-oss-cn-beijing.aliyuncs.com';
//    const OSS_HOST          = 'http://dapeng-video.oss-cn-beijing.aliyuncs.com';
    const OSS_INTERNAL_HOST = 'http://zhijin-vod.vpc100-oss-cn-hangzhou.aliyuncs.com';
    const OSS_HOST          = 'http://zhijin-vod.oss-cn-hangzhou.aliyuncs.com';

    const OSS_LIVE_INTERNAL_HOST = 'http://zhijin-live.vpc100-oss-cn-hangzhou.aliyuncs.com';
    const OSS_LIVE_HOST          = 'http://zhijin-live.oss-cn-hangzhou.aliyuncs.com';

    const OSS_ENDPOINT = 'oss-cn-hangzhou.aliyuncs.com';
    const OSS_BUCKET = 'zhijin-vod';
}


     /**
     * 學員上傳作業圖片
     *
     *
     */
    public function onUploadAvatar()
    {
        // if (!$this->check()) {
        //     return CommonConst::getErrorChineseDesc(CommonConst::USER_NOT_LOGIN);
        // }

        $user  = new User();
        $userInfo = $user->getUser();
        $teacherHomeworkId = $this->param('id');
        if(empty($userInfo->id)){
            //2013 未登入
            return CommonConst::getErrorChineseDesc(CommonConst::USER_NOT_LOGIN);
        }

        $file = Input::file('myfile');
        // 檔案是否上傳成功
        if ($file->isValid()) {
            // 獲取檔案相關資訊
            $originalName = $file->getClientOriginalName(); // 檔案原名
            $ext = $file->getClientOriginalExtension();     // 副檔名
            $realPath = $file->getRealPath();   //臨時檔案的絕對路徑
            $type = $file->getClientMimeType();     // image/jpeg
            // 上傳檔案
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用我們新建的uploads本地儲存空間(目錄)
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
            $url = storage_path('app/uploads/homework/'.$filename);
            $studentHomeworkId = StudentHomeworkModel::where('user_id',$userInfo->id)->where('teacher_homework_id',$teacherHomeworkId)->first();
            if(!empty($studentHomeworkId)){
                $ossUrl = $this->imgToOss($userInfo->id,$studentHomeworkId->id,$imgPath = $url);
                return ['msg' => $ossUrl];
            }
        }else{
            return CommonConst::getErrorChineseDesc(CommonConst::UPLOAD_FILE_ERROR);
        }
        //return  ['msg'  => $url];
    }


       public function onGetHomeworkResources(){
        $user  = new User();
        $userInfo = $user->getUser();
        $description = post('description');
        $teacherHomeworkId = $this->param('id');
        $homeworkResources = StudentHomeworkModel::where('user_id', $userInfo->id)
            ->where('teacher_homework_id',$teacherHomeworkId)
            ->with('homeworkResources')
            ->get();
        foreach ($homeworkResources as $key => $homeworkResource) {
            $length = 1000-mb_strlen($homeworkResource['description'],'UTF-8');
            $homeworkResources[$key]->length = $length;
        }

        $this->page['homeworkResources'] = $homeworkResources;
    }


     
    public function onPublishStudentHomework()
    {
        $user  = new User();
        $userInfo = $user->getUser();
        $description = post('description');
        $teacherHomeworkId = $this->param('id');
        $uploads = post('uploadImage');
        $uid = $userInfo->id;
        $videoConfig = require_once __DIR__ . "/../../../../config/video.php";
        $studentHomeworkId = StudentHomeworkModel::where('user_id',$userInfo->id)
                ->where('teacher_homework_id',$teacherHomeworkId)
                ->with('homeworkResources')
                ->first();
        //資料庫已經存在的
        $imgUrl = StudentHomeworkResources::where('student_homework_id',$studentHomeworkId->id)
                ->lists('disk_name','id');
        //新增圖片資源(編輯進行對比)
        if(!empty($uploads)){
            $addUploadImages  = array_diff($uploads,$imgUrl);
            $deleteImages = array_diff($imgUrl,$uploads);
            //新增關聯學生作業圖片
            foreach ($addUploadImages as $key => $upload) {
                // $substr = explode("homework/",$upload);
                // $substr = preg_replace('/.*\//','',$upload);
                $arr=explode("/", $upload);
                //獲取最後一個/後邊的字元
                $substr=$arr[count($arr)-1];
                // trace_log($upload,$substr);
                //伺服器上檔案路徑
                $readImgPath = $videoConfig['HOMEWORK_IMAGE_READ_PATH'] . "$uid/$studentHomeworkId->id/$substr";
                $image = Storage::disk('uploads')->get($substr);
                $fileSize = Storage::disk('uploads')->size($substr);
                $imageType = Storage::disk('uploads')->mimeType($substr);
                $updateTime = Storage::disk('uploads')->lastModified($substr);
                StudentHomeworkResources::insert([
                'student_homework_id' => $studentHomeworkId->id,
                'disk_name' => $readImgPath,
                'file_name' => $substr,
                'file_size' => $fileSize,
                'content_type' =>$imageType,
                'created_at' => date('Y-m-d-H-i-s',$updateTime),
                ]);
            }
            //刪除編輯的圖片
            foreach ($deleteImages as $key => $image) {
                $id = StudentHomeworkResources::where('disk_name',$image)->where('student_homework_id',$studentHomeworkId->id)->lists('id');
                StudentHomeworkResources::where('id',$id)->delete();
            }

            $sId = Db::table('dapeng_student_homework')->where('id',$studentHomeworkId->id)
                       ->first();

            Db::table('dapeng_student_homework')->where('id',$sId->id)->update(['description' => $description,'is_submit' => 1, 'submit_at' => date('Y-m-d-H-i-s',time())]);

        }else{
            return CommonConst::getErrorChineseDesc(CommonConst::UPLOAD_FILE_FAILE);
        }
        return CommonConst::getErrorChineseDesc(CommonConst::SUCCESS);
    }

     
     /**
     * @return oss img url
     * @description img to oss    上傳到oss上
     */
    public function imgToOss($uid = null,$homeworkid,$imgPath = null)
    {
        $videoConfig = require_once __DIR__ . "/../../../../config/video.php";
        $obj = new writeAuth();

        $file   = $imgPath;

        $tempImgName = pathinfo($imgPath);
        $baseName = $tempImgName['basename'];

        $object = $videoConfig['HOMEWORK_UPLOAD_DIR'] . "$uid/$homeworkid/$baseName";
        $readImgPath = $videoConfig['HOMEWORK_IMAGE_READ_PATH'] . "$uid/$homeworkid/$baseName";

        //這裡如果有錯誤的話 會直接報錯
        $obj->avatar($object, $file);
        $obj->avatarAcl($object);

        return $readImgPath;
    }




相關文章