tp5.1阿里云oss上传功能整合

1.阿里云sdk 获取

composer require aliyuncs/oss-sdk-php

2.引入类库

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

3.后端上传代码实现  我这里用的 webupload  返回格式如下

    // 单图上传
    public function doupload()
    {
        // 配置文件
        $alioss = config('alioss.');
        $accessKeyId = $alioss['accessKeyId'];
        $accessKeySecret = $alioss['accessKeySecret'];
        $endpoint = $alioss['endpoint'];
        $bucket = $alioss['bucket'];
        $file = request()->file('file');
        // 文件名称生成
        $file_name = sha1(date('YmdHis',time()).uniqid()).'.'.pathinfo($file->getInfo()['name'],PATHINFO_EXTENSION);
        // 文件路径生成
        $folder = input('param.folder');
        $file_path = config('oss_save_path').'/'.$folder. '/' .date('Ymd');
        $url =  $file_path .'/'. $file_name;
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $result =$ossClient->uploadFile($bucket,$url,$file->getInfo()['tmp_name']);
            if (isset($result['info']['http_code']) AND $result['info']['http_code']==200) {
                $result=['code'=>1,'url'=>$result['info']['url'],'msg'=>'上传成功'];
            }else{
                $result=['code'=>0,'url'=>'','msg'=>'上传错误'];
            }
        } catch(OssException $e) {
            $msg = $e->getMessage();
            $result=['code'=>0,'url'=>'','msg'=> $msg];
        }
        return json($result);
    }  

4.注意点:

1.bucket 我是提前创建的并写在配置文件中

2.上传路径格式要注意 我在接入时前面多添加了一个/ 导致出错  

5.阿里云镜像替换

1.composer中国区的镜像源 全局替换
    composer config -g repositories.packagist composer http://packagist.phpcomposer.com
2. 阿里云 composer 镜像 全局替换
    composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

 

你可能感兴趣的:(php,thinkphp)