1. composer 安装 SDK 依赖
sdk 地址为 https://github.com/aliyun/aliyun-oss-php-sdk
2. 代码实现
<?php
/**
* Created by PhpStorm.
* User: nwei
* Date: 2019/1/4
* Time: 17:02
*
* .--, .--,
* ( ( \.---./ ) )
* '.__/o o\__.'
* {= ^ =}
* > - <
* / \
* // \\
* //| . |\\
* "'\ /'"_.-~^`'-.
* \ _ /--' `
* ___)( )(___
* (((__) (__))) 高山仰止,景行行止.虽不能至,心向往之.
*/
namespace App\Tools;
use OSS\Core\OssException;
use OSS\OssClient;
class AliyunOss
{
private $accessKeyId = 'xxx';
private $accessKeySecret = 'xx';
private $endpoint = 'oss-cn-beijing.aliyuncs.com';
private $bucket = 'nwei-oss-bucket';
public function uploadFile($oss_path, $file_path)
{
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->uploadFile($this->bucket, $oss_path, $file_path);
return $oss_path;
} catch (OssException $e) {
operate_log("-1", 'AliOss', '文件上传失败:' . $e->getErrorCode() . ':' . $e->getErrorMessage() . "未上传的文件名 " . $file_path);
return null;
}
}
}
- $accessKeyId 和 $accessKeySecret 的获取的位置
- $endpoin 地域节点的获取位置
- $bucket 的获取位置
2. 使用示例
// 阿里云OSS
Route::get('aliyun-oss', function () {
$oss = new \App\Tools\AliyunOss();
$oss_path = "test/".str_random().".jpg";
$rs = $oss->uploadFile($oss_path,public_path('images/cat.jpg'));
dd($rs);
});
我用的是 Laravel 框架,在我的 public/images 文件夹下有张图片 cat.jpg,我要把这张图上传到阿里云的 oss 上,路径为 test 文件的下. uploadFile() 方法返回图片的路径
如果我们需要通过我们的 $endpoint 地域节点访问我们的图片,需要将我们的 Bucket 读写权限设置成公共读,
访问我们刚才上传的图片