PHP上传到OSS封装方法



//此方法为控制器方法
public function uploadImages(Request $request)
    {

        $fileNames = $request->input('fileName');
        $file = $request->file('file');
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $oss = new Oss();
            $extension = $file->extension();
            $allowedExtensions = ["png", "jpg", "gif", "jpeg"];
            if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowedExtensions)) {
                return json_encode(['error' => '您上传的图片格式不符,请重新上传']);
            }
            $fileName = md5(time()) . '.' . $extension;
            $file = $file->storeAs('photo', $fileName);
            $files = storage_path() . '/app/photo/' . $fileName;
            $result = $oss->uploadFileToOss($files, 'volunteer/');
            if (isset($result['filename']) && !empty($result['filename'])) {
                $imgUrl = $oss->getOssUploadFileUrl($result['filename'], 'volunteer/');
                unlink($files);
            }
            $data = [
                'error' => 0,
                'url'   => $imgUrl
            ];
            return $data;
        }
    }

//该方法为在app/底下创建目录 Service然后创建Oss.php
<?php
namespace App\Service;
use OSS\Core\OssException;
use OSS\OssClient;
class Oss{
    /**
     * @var
     */
    private $bucket;

    /**
     * @var
     */
    private $access_id;

    /**
     * @var
     */
    private $access_key;

    /**
     * @var
     */
    private $endpoint;

    /**
     * Oss constructor.
     */
    public function __construct()
    {
        $this->bucket =  trim(config('oss.oss_bucket'));
        $this->access_id =  trim(config('oss.access_id'));
        $this->access_key =  trim(config('oss.access_key'));
        $this->endpoint = trim(config('oss.oss_endpoint'));
    }

    /**
     * 取得Oss图片数据源
     * @param string $ossFileName
     * @return string 文件全路径
     */
    public  function getArticleShareIcon($ossFileName,$oss_dir){
        return $this->getUploadOssFileByConfig($ossFileName,$oss_dir);
    }

    /**
     * 上传文件到Oss
     * @param string $fileName
     * @param $oss_dir
     * @return null
     * @throws OssException
     */
    public function uploadFileToOss($fileName,$oss_dir){
        //验证oss_dir
        if (empty($oss_dir)){
            die('oss_dir 不允许为空');
        }
        $ossClient = new OssClient($this->access_id,$this->access_key, $this->endpoint);
        if (!$ossClient->doesObjectExist($this->bucket,$oss_dir)){
            $ossClient->createObjectDir($this->bucket,$oss_dir);
        }
        $ext = strrchr($fileName, '.');
        $hashFileName = sha1($fileName.time().rand(0,100)).$ext;
        $hashFileNameWithPath = $oss_dir.$hashFileName;
        //随机文件名防止重复
        $result = $ossClient->uploadFile($this->bucket,$hashFileNameWithPath,$fileName);
        if (isset($result['info'])){
            $result['info']['filename'] = $hashFileName;
            $result['info']['cdnUrl'] = $this->getOssUploadFileUrl($hashFileName,$oss_dir);
        }
        return isset($result['info']) ? $result['info'] : false;
    }
    /**
     * 获取路径
     * @param $oss_file
     * @param $oss_dir
     * @return string
     */
    public  function getOssUploadFileUrl($oss_file,$oss_dir){
        if (empty($oss_dir) || empty($oss_file)){
            die('oss_dir oss_file 不允许为空');
        }
        return env("OSS_CDN_ENDPOINT").$oss_dir.$oss_file;
    }
}
//在config目录下创建confing.php然后将oss所需key等值放入.env文件
<?php
/**
 * Oss 配置文件
 */
return [
    /**
     * oss access_id
     */
    'access_id' => env('OSS_ACCESS_ID'),

    /**
     * oss_access_key
     */
    'access_key' => env('OSS_ACCESS_KEY'),

    /**
     * oss bucket
     */
    'oss_bucket' => env('OSS_BUCKET'),

    /**
     * oss_endpoint_test
     */
    'oss_endpoint' => env('OSS_ENDPOINT'),

    /**
     * oss_cnd_endpoint
     */
    'oss_cdn_endpoint' => env('OSS_CDN_ENDPOINT'),
];

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值