TP5 阿里云OSS上传文件存储

购买相关产品以后,进入产品,创建一个bucket
在这里插入图片描述
代码贴图

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/13
 * Time: 11:51
 */

namespace app\api\controller;


use think\Controller;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Log;


class Oss extends Controller
{
    static $acsClient = null;
    protected $accessKeyId = null;
    protected $accessKeySecret = null;
    protected $endpoint = null;
    protected $bucket = null;

    public function _initialize()
    {
    	//根据自己的SDK路由定义
        require_once EXTEND_PATH . '/../vendor/oss/autoload.php';

        // AccessKeyId
        $this->accessKeyId = "AccessKeyId";
        // AccessKeySecret
        $this->accessKeySecret = "AccessKeySecret";
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        $this->endpoint = "Endpoint外网访问节点";
        // 存储空间名称
        $this->bucket = "up-nc-video";

    }

    /**
     * 删除OSS相关链接文件
     *$object  链接
     * @return DefaultAcsClient
     */
    public function delOss($object)
    {

//链接举例   $object = 'upload/video/2020-04-15%2009%3A13%3A54-83767f8bd59dea5acddb379210398028.mp4';
        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret,$this->endpoint);

            $res = $ossClient->deleteObject($this->bucket, $object);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            Log::record('删除失败原因:'.$e->getMessage(),'notice');
            return false;
        }
        print(__FUNCTION__ . ": OK" . "\n");
    }

    /**
     * 上传文件
     * @param string $filename 文件名
     * @param $file 文件
     * @return bool|null
     */
    public function uploadFile($filename = '', $file)
    {

        // 设置文件名称。
        $object = 'upload/video/' . date("Y-m-d h:i:s") . '-' . $filename;
// <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。

        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

            $res = $ossClient->uploadFile($this->bucket, $object, $file['tmp_name']);

            return $res;
        } catch (OssException $e) {
            Log::record('上传失败原因:'.$e->getMessage(),'notice');
            return false;
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值