PHP之OSS

首先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;
    }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP中的工厂模式可以用于创建对象,而不需要直接使用new关键字实例化。对于使用OSS(对象存储服务)的工厂模式,你可以按照以下步骤进行操作: 1. 创建一个接口(或抽象类)来定义OSS客户端的方法,例如`OSSClientInterface`。 ```php interface OSSClientInterface { public function upload($file); // 其他操作方法 } ``` 2. 创建一个实现了该接口的具体类,例如`AliyunOSSClient`。该类应该包含具体的OSS操作逻辑。 ```php class AliyunOSSClient implements OSSClientInterface { public function upload($file) { // 实现上传文件到阿里云OSS的逻辑 } // 其他操作方法的实现 } ``` 3. 创建一个工厂类,例如`OSSClientFactory`,用于根据需要创建不同的OSS客户端对象。 ```php class OSSClientFactory { public static function createClient($provider) { switch ($provider) { case 'aliyun': return new AliyunOSSClient(); // 可以添加其他OSS服务提供商的创建逻辑 default: throw new Exception('Unsupported OSS provider'); } } } ``` 4. 在代码中使用工厂类来创建所需的OSS客户端对象。 ```php $ossProvider = 'aliyun'; // 可以根据需要设置OSS服务提供商 $ossClient = OSSClientFactory::createClient($ossProvider); // 使用ossClient进行操作 $ossClient->upload('example.jpg'); ``` 通过使用工厂模式,你可以方便地根据需要创建不同的OSS客户端对象,而无需直接实例化具体的实现类。这样可以提高代码的灵活性和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值