ThinkPHP上传文件到阿里云OSS

首先需要4个参数

$accessKeyId = "ID";
$accessKeySecret = "秘钥";
$endpoint = "节点";
$bucket = '存储空间名';

第一二个参数在阿里云用户AccessKey 管理里面获取

第三四个参数在阿里云OSS列表管理里面获取

需要注意该对象存储读写权限要设置为公开的,私有的外网无法访问

使用composer 安装阿里云OSS扩展:

composer require aliyuncs/oss-sdk-php

阿里云上传文件服务类
appcommonserviceAliyunOss.php

<?php
/**
 * Created by PhpStorm.
 * User: Pasa吴
 * Date: 2020/4/29
 * Time: 15:28
 */

namespace app\common\service;

use OSS\Core\OssException;
use OSS\OssClient;

class AliyunOss
{
    //ID
    protected $accessKeyId;
    //秘钥
    protected $accessKeySecret;
    //节点
    protected $endpoint;
    //存储空间名
    protected $bucket;

    public function __construct(array $config)
    {
        $this->accessKeyId     = $config['accessKeyId'];
        $this->accessKeySecret = $config['accessKeySecret'];
        $this->endpoint        = $config['endpoint'];
        $this->bucket          = $config['bucket'];
    }

    function upload($dst, $src)
    {
        //获取对象
        $auth = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

        try {
            //上传图片
            $result = $auth->uploadFile($this->bucket, $dst, $src);
            return $result['info']['url'];
        } catch (OssException $e) {
            return $e->getMessage();
        }
    }
}

调用方法

    public function uploadFileForm()
    {
        $scr = $_FILES['file']['tmp_name'];
        $ext = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.') + 1); // 上传文件后缀
        $dst = md5(time()) . '-' . $scr . '.' . $ext;     //上传文件名称

        $alioss           = new AliyunOssService([
            'accessKeyId'     => 'xxx',//修改为你对应参数
            'accessKeySecret' => 'xxx',//修改为你对应参数
            'endpoint'        => 'xxx',//修改为你对应参数
            'bucket'          => 'xxx',//修改为你对应参数
        ]);
        $this->res['url'] = $alioss->upload($dst, $scr);

        if ($this->res) {
            $this->show([SUCCESS, MES_SUCCESS, $this->res]);
        }
        $this->show([FAILED, MES_FAILED, $this->res]);
    }

Pasa吴PHP博客
请先登录后发表评论
  • 最新评论
  • 总共0条评论