ThinkPHP上传文件到阿里云 OSS 对象存储

  • Post author:
  • Post category:php




一、准备工作


1. 开通阿里云 OSS 服务


对象存储 OSS >>>



2. 安装 OSS PHP SDK
composer require aliyuncs/oss-sdk-php


查看相关文档 >>>



二、修改配置文件

开通 OSS 服务后把相应的配置项填写即可(这里是

ThinkPHP6



config/upload.php

):

/*
* 自定义配置
*/
'aliOss' => [
   'accessKeyId' => '',
   'accessKeySecret' => '',
   'endpoint' => '',
   'bucket' => ''
]


三、代码实现
use OSS\Core\OssException;
use OSS\OssClient;
use think\exception\ValidateException;

// 文件上传至阿里云对象存储(tp6)
public function aliOss($file)
{
    try {
        $fileValidate = ['fileSize' => 5242880, 'fileExt' => 'jpg,png,jpeg'];
        validate(['image' => $fileValidate])->check(['image' => $file]);
        $ossClient = new OssClient(config('upload.aliOss.accessKeyId'), config('upload.aliOss.accessKeySecret'), config('upload.aliOss.endpoint'));
        $ext = strrchr($file->getOriginalName(), '.');
        $object = 'images/'.date('YmdHis').mt_rand(000, 999).$ext;
        $result = $ossClient->putObject(config('upload.aliOss.bucket'), $object, $file->getLinkTarget());
        if (!empty($result) && isset($result['info']['url'])) {
            return ['code' => 1, 'msg' => '上传成功', 'data' => ['url' => $result['info']['url']]];
        }
        return ['code' => 0, 'msg' => '上传失败', 'data' => ['url' => '']];
    } catch (ValidateException $validateException) {
        return ['code' => 0, 'msg' => $validateException->getMessage(), 'data' => ['url' => '']];
    } catch (OssException $ossException) {
        return ['code' => 0, 'msg' => $ossException->getMessage(), 'data' => ['url' => '']];
    }
}


四、可能出现的问题

  1. RequestCoreException: cURL error: SSL certificate problem.



    SDK

    文件中找到

    src/OSS/Http/RequestCore.php

    ,修改:

    public $ssl_verification = false;
    

    不验证 SSL 证书即可。



版权声明:本文为ZhangJiWei_2019原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。