由于工作中需要使用 阿里云OSS的SDK上传图片实例,经过在网上搜索和自己的实验,已经成功的在项目中使用了,下面的是例子:
1.先用composer 下载oss的sdk到框架的vendor中
使用composer下载的会通过composer自动加载到项目中,如果是copy到项目中的,则需要去添加配置是的能自动加载:
2. 在根目录/common/里面新建Aliyunoss.php文件。
3. 代码:``<?php
namespace app\common;
use Yii;
use yii\base\Component;
use OSS\OssClient;
use OSS\Croe\OssException;
class Aliyunoss extends Component
{
public static $oss;
public function __construct()
{
parent::__construct();
//获取阿里云oss的accessKeyId
$accessKeyId = Yii::$app->params['oss']['accessKeyId'];
//获取阿里云oss的accessKeySecret
$accessKeySecret = Yii::$app->params['oss']['accessKeySecret'];
//获取阿里云oss的endPoint
$endpoint = Yii::$app->params['oss']['endPoint'];
//实例化OssClient对象
self::$oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
}
/**
* 使用阿里云oss上传文件
* @param $object 保存到阿里云oss的文件名
* @param $filepath 文件在本地的绝对路径
* @return bool 上传是否成功
*/
public function upload($object, $filepath)
{
$bucket = Yii::$app->params['oss']['bucket']; //获取阿里云oss的bucket
$result=array();
try{
$getOssInfo=self::$oss->uploadFile($bucket, $object, $filepath);
$result['url'] = $getOssInfo['info']['url'];
}catch(OssException $e){
var_dump($e->getMessage());
return;
};
$url = $result['url'];
return $url;
}
//下载
public function down($object) {
$bucket = Yii::$app->params['oss']['bucket']; //获取阿里云oss的bucket
$localfile ="yuzengyuan."."jpg";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $localfile,
);
try {
$bucket = Yii::$app->params['oss']['bucket'];
self::$oss->getObject($bucket, $object,$options);
} catch( OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK, " .$localfile. "\n");
}
//判断是否存在文件
function doesObjectExist($object) {
try{
$bucket = Yii::$app->params['oss']['bucket'];
$exist = self::$oss->doesObjectExist($bucket, $object);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
return $exist;
}
/**
* 删除指定文件
* @param $object 被删除的文件名
* @return bool 删除是否成功
*/
public function delete($object)
{
$res = false;
$bucket = Yii::$app->params['oss']['bucket']; //获取阿里云oss的bucket
if (self::$oss->deleteObject($bucket, $object)){ //调用deleteObject方法把服务器文件上传到阿里云oss
$res = true;
}
return $res;
}
}``
3.在配置文件中添加:
Aliyunoss' => [ 'class' => 'app\common\Aliyunoss', ],
4.项目中调用:
返回的就是图片的路径