在阿里云开通阿里云对象存储oss功能后, php对接阿里oss ,按以下步骤减少配置难度。
安装aliyuncs/oss-sdk-php
composer require aliyuncs/oss-sdk-php
php 使用
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\WechatController;
use Illuminate\Support\Facades\Cache;
use OSS\OssClient;
use App\Http\Controllers\Api\ImgsizeController;
class OssController extends Controller
{
public $accessKeyId = "";//<您从OSS获得的AccessKeyId>
public $accessKeySecret = "";//<您从OSS获得的AccessKeySecret>
public $endpoint = "";//<您选定的OSS数据中心访问域名,例如oss-cn-hangzhou.aliyuncs.com>
public $bucket = "";//<您使用的Bucket名字,注意命名规范>
//oss连接对象
public function getossclient(){
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
return $ossClient;
}
//上传文件到oss
public function uploadoss(Request $request){
$content=$request->file('files');
$object = "active/".date("Y/m/d")."/".uniqid().".".$content->getClientOriginalExtension();//<您使用的Object名字,注意命名规范>
try {
$ossClient=$this->getossclient();
$ossClient->uploadFile($this->bucket, $object, $content);
} catch (OssException $e) {
print $e->getMessage();
}
return ['code'=>1,'msg'=>"上传成功"];
}
//获取oss数据列表
public function getosslist(Request $request){
$prefix = $request->input('path','');
$delimiter = "/";
$nextMarker = '';
$maxkeys = 1000;
$options = array(
'delimiter' => $delimiter,
'prefix' => $prefix,
'max-keys' => $maxkeys,
'marker' => $nextMarker,
);
try {
$ossClient=$this->getossclient();
$listObjectInfo = $ossClient->listObjects($this->bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
$objectList = $listObjectInfo->getObjectList(); // object list
// echo("<pre>");
// var_dump($objectList);
$prefixList = $listObjectInfo->getPrefixList(); // directory list
if (!empty($prefixList)) {
foreach ($prefixList as $prefixInfo) {
echo "<img src='https://rdjmobile.oss-cn-beijing.aliyuncs.com/rdjother/other/%E6%96%87%E4%BB%B6%E5%A4%B9.png' style='vertical-align:middle '><a href='/getosslist?path=".$prefixInfo->getPrefix(). "'>".$prefixInfo->getPrefix() . "</a><br>";
}
}
if (!empty($objectList)) {
foreach ($objectList as $objectInfo) {
echo "<img src='https://rdjmobile.oss-cn-beijing.aliyuncs.com/rdjother/other/%E6%96%87%E4%BB%B6.png' style='vertical-align:middle '><a href='https://rdjmobile.oss-cn-beijing.aliyuncs.com/".$objectInfo->getKey() . "'>".$objectInfo->getKey() . "</a><br>";
}
}
}
//删除文件
public function deleteoss(){
$object = "rdjother/other/图 片.png";
try {
$ossClient=$this->getossclient();
$ossClient->deleteObject($this->bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
return ['code'=>1,'msg'=>"删除成功"];
}
}
效果图