Thinkphp5.1上传文件到阿里云OSS

上传文件,阿里云OSS上传,文件上传到OSS,OSS文件上传,OSS上传

上传文件到阿里云OSS里,需要注意的是,文件要先传到服务器或者用本地的绝对路径。

根据文档,先安装SDK:

composer require aliyuncs/oss-sdk-php


资源名称就是Bucket列表里的名称:

07/5a12641073c460229f78dcf71a9869.png


文件夹列表:

53/6b52c624cbd75ab594cd6e07a1c1e0.png


上传方法放到common.php里:

//上传文件到阿里云OSS

function uploadOSS($file){

    $accessKeyId                    = config('app.aliyunoss.accessKeyId');

    $accessKeySecret                = config('app.aliyunoss.accessKeySecret');

    $endpoint                       = config('app.aliyunoss.endpoint');

    // 填写Bucket名称,例如examplebucket。

    $bucket                         = "资源名称";//上面的bucket列表里的名字,要传到哪个bucket里就填哪个名字

    // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。

    $object                         = "这里是阿里云OSS文件夹名字(传到这个文件夹里,图2)".str_replace('uploads','',$file);

    // <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。

    // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。

    $filePath                       = Env::get('root_path') . 'public/' .$file;

    try {

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        $ossClient->uploadFile($bucket, $object, $filePath);

    } catch (OssException $e) {

        print $e->getMessage();

    }

}

然后在需要调用上传的地方调用该方法即可:

uploadOSS($image['content']);
注意:该上传没有返回值