一、安装SDK(composer)
composer require aliyuncs/oss-sdk-php
二、创建controller命名Oss
<?php
namespace app\common\controller;
use OSS\Core\OssException;
use OSS\OssClient;
class Oss{
public function __construct(){
//按照自己路径引入
if (is_file(__DIR__ . '/../../../vendor/autoload.php')) {
require_once __DIR__ . '/../../../vendor/autoload.php';
}
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
$this->accessKeyId = "按照自己的accessKeyId配置";
$this->accessKeySecret = "按照自己的accessKeySecret配置";
// Endpoint以北京为例,其它Region请按实际情况填写。
$this->endpoint = "http://oss-cn-beijing.aliyuncs.com";
}
/**
* 创建储存空间
* */
public function createCapacity($bucketName = 'aliyun-litemob-adn'){
// 存储空间名称
$bucket = $bucketName;
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->createBucket($bucket);
echo '创建成功';
} catch (OssException $e) {
print $e->getMessage();
}
}
/**
* 上传文件
* */
public function uploadFiles($bucketName = 'aliyun-litemob-adn',$objectName = 'adfdafdsafad'){
// 存储空间名称
$bucket= $bucketName;
// 文件名称
$object = $objectName;
$content = "Hello!";
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->putObject($bucket, $object, $content);
echo '上传成功';
} catch (OssException $e) {
print $e->getMessage();
}
}
/**
* 下载文件
* */
public function downloadFile($bucketName = 'aliyun-litemob-adn',$objectName = 'adfdafdsafad'){
// 存储空间名称
$bucket= $bucketName;
// 文件名称
$object = $objectName;
try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$content = $ossClient->getObject($bucket, $object);
print("文件内容: " . $content);
} catch (OssException $e) {
print $e->getMessage();
}
}
}
1、创建储存库
2、上传文件
3、下载文件
只以这几个来测试了,其他的都是一样的道理!