- 首先通过Composer进行引入
composer require aliyuncs/oss-sdk-php
- 然后直接用下面文件,然后更改自己的命名空间(有其他需要直接看文档复制粘贴就完事了)阿里云文档
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;
class OssUtilController extends Controller
{
protected $accessKeyId;
protected $accessKeySecret;
protected $endpoint;
protected $bucket;
public function __construct()
{
$this->accessKeyId = config('aliyun.accessKeyId');
$this->accessKeySecret = config('aliyun.accessKeySecret');
$this->endpoint = config('aliyun.endpoint');
// 存储空间名称
$this->bucket = config('aliyun.ossBucket');
}
/**
* @desc 添加文件
* @param $filePath 上传的文件
* @param $savePath 保存到oss的路径
*/
public function uploadFile($filePath, $savePath)
{
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->uploadFile($this->bucket, $savePath, $filePath);
} catch (OssException $e) {
return ['code' => 1, 'msg' => $e->getMessage()];
}
return ['code' => 0];
}
/**
* @desc 删除文件
* @param deletePath oss的路径
*/
public function deleteFile($deletePath)
{
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->deleteObject($this->bucket, $deletePath);
} catch (OssException $e) {
return ['code' => 1, 'msg' => $e->getMessage()];
}
return ['code' => 0];
}
/**
* @desc 下载文件
* @param string $downLoadFile 下载文件地址
* @param string $saveFile 保存地址
*/
public function downLoadFile($downLoadFile, $saveFile)
{
$localfile = $saveFile;
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $localfile
);
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->getObject($this->bucket, $downLoadFile, $options);
} catch (OssException $e) {
return ['code' => 1, 'msg' => $e->getMessage()];
}
return ['code' => 0];
}
}
- 生成一个方法 依赖注入 然后直接调用
function useAlyunOos(OssUtilController $oss)
{
$data = $ossUpload->uploadFile($srcFile, $relatePath);
if ($data['code']) {
return $this->returnJson($data['msg']);
}
}
补充:
- 在这里申请Accesskey
__construct函数 自己在env中写对应的 或者说直接替换成对应的的即可