简单实现上传阿里云存储功能
首先:composer安装oss扩展
composer require aliyuncs/oss-sdk-php
然后:引入类库
<?php
namespace app\home\controller;
vendor('aliyuncs.oss-sdk-php.autoload');
use OSS\OssClient;
use OSS\Core\OssException;
use think\Controller;
class TPOSS extends Controller
{
public $accessKeyId = "---"; //keyid
public $accessKeySecret = "---"; //keysecret
public $endpoint = "oss-cn-beijing.aliyuncs.com";
public $bucket = "---"; //bucket 名称
/**
* oss 上传图片或其他文件
* @param $object oss存储地址
* @param $filePath 带路径文件名
*/
public function uploadOssFile($object, $filePath)
{
$object = $object . '/' . $filePath;//想要保存文件的名称
$file = './uploads\\' . $filePath;//文件路径,必须是本地的。
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$data = $ossClient->uploadFile($this->bucket, $object, $file);
} catch (OssException $e) {
return false;
}
return $data['info']['url'];
}
/**
* oss判断文件是否存在
* @param $object 要判断的文件
*/
public function checkFileExist($object)
{
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$exist = $ossClient->doesObjectExist($this->bucket, $object);
} catch (OssException $e) {
return false;
}
return $exist;
}
/**
* oss 删除多个文件
* @param $objects array 多个文件
* @return bool
*/
public function deleteFiles($objects)
{
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->deleteObjects($this->bucket, $objects);
} catch (OssException $e) {
return false;
}
return true;
}
/**
* 获取指定文件件下的文件列表
* @param string $prefix 指定目录
* @param string $nextMarker 从那个文件开始(不包含)(获取文件夹下所有文件的话,值与$prefix相同)
* @param string $delimiter 对文件名称进行分组的一个字符。CommonPrefixes是以delimiter结尾,并有共同前缀的文件集合。
* @param string $maxkeys 列举文件的最大个数。默认为100,最大值为1000。
* @return bool array 返回文件列表
*/
public function listObject($prefix = '', $nextMarker = '', $delimiter = '', $maxkeys = '')
{
try {
$options = array(
'prefix' => $prefix,
'marker' => $nextMarker,
'delimiter' => $delimiter,
'max-keys' => $maxkeys,
);
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$listObjectInfo = $ossClient->listObjects($this->bucket, $options);
} catch (OssException $e) {
return false;
}
// $nextMarker = $listObjectInfo->getNextMarker();
$listObject = $listObjectInfo->getObjectList();
// $listPrefix = $listObjectInfo->getPrefixList();
if (!empty($listObject)) {
$list = array();
foreach ($listObject as $objectInfo) {
$list[] = $objectInfo->getKey();
}
return $list;
} else {
return false;
}
}
}
最后:编写上传代码:
public function img(){
$file = request()->file('file');
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
$img = $info->getSaveName();
} else {
// 上传失败获取错误信息
$this->error($file->getError());
}
//上传云存储
$obj = new \app\home\controller\TPOSS();
$img = $obj->uploadOssFile('month', $img); //. "?x-oss-process=style/300x500";
return json($img)
}