一.YII2使用阿里云Oss
composer安装Oss-Skd包 地址 :: yii2.0整合阿里云oss php sdk(一) - 源码 - Yii Framework 中文网https://www.yiichina.com/code/1078
实例代码
//根据使用composr安装的skd 编写的上传 ,此处在sdk包中的OssClient类做出了更改
/**
* $path 形式为 '/image/2019-02-26/aa.png' 无需携带域名
*/
public function ossUpload($path,$file){
$config = \Yii::$app->params['alioss'];
$obj = new OssClient($config['accesskey'], $config['secret'], $config['endpoint']);
$res = $obj->uploadFile($config['bucket'], $path, $file); //此处返回的是对象,乱七八糟一大堆 只有一个status 和header['oss-request-url']有用
// if(isset($res->header))
if(isset($res->status) and $res->status == 200)
{
return $res->header['oss-request-url']; //此处url可直接访问 只不过是原图未压缩
}
return false;
}
OssClient的修改
//构造方法的更改 这些更改只是将参数挪动到了 构造方法里边
public function __construct($accessKeyId, $accessKeySecret, $endpoint, $isCName = false, $securityToken = NULL, $requestProxy = NULL)
{
$accessKeyId = trim($accessKeyId);
$accessKeySecret = trim($accessKeySecret);
$endpoint = trim(trim($endpoint), "/");
if (empty($accessKeyId)) {
throw new OssException("access key id is empty");
}
if (empty($accessKeySecret)) {
throw new OssException("access key secret is empty");
}
if (empty($endpoint)) {
throw new OssException("endpoint is empty");
}
$this->hostname = $this->checkEndpoint($endpoint, $isCName);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
$this->securityToken = $securityToken;
$this->requestProxy = $requestProxy;
self::checkEnv();
}
//执行上传的方法的更改
public function uploadFile($bucket, $object, $file, $options = NULL)
{
$this->precheckCommon($bucket, $object, $options);
OssUtil::throwOssExceptionWithMessageIfEmpty($file, "file path is invalid");
$file = OssUtil::encodePath($file);
if (!file_exists($file)) {
throw new OssException($file . " file does not exist");
}
$options[self::OSS_FILE_UPLOAD] = $file;
$file_size = filesize($options[self::OSS_FILE_UPLOAD]);
$is_check_md5 = $this->isCheckMD5($options);
if ($is_check_md5) {
$content_md5 = base64_encode(md5_file($options[self::OSS_FILE_UPLOAD], true));
$options[self::OSS_CONTENT_MD5] = $content_md5;
}
if (!isset($options[self::OSS_CONTENT_TYPE])) {
$options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object, $file);
}
$options[self::OSS_METHOD] = self::OSS_HTTP_PUT;
$options[self::OSS_BUCKET] = $bucket;
$options[self::OSS_OBJECT] = $object;
$options[self::OSS_CONTENT_LENGTH] = $file_size;
$response = $this->auth($options);
return $response;
}
二.图片压缩处理 只需要携带对应的后缀即可
http://demo.oss-cn-xxxxx.aliyuncs.com/test.jpg?x-oss-process=image/quality,q_60
原图清晰度的60%
http://demo.oss-cn-xxxxx.aliyuncs.com/test.jpg?x-oss-process=image/quality,q_80
原图清晰度的80%
裁剪
http://demo.oss-cn-xxxxx.aliyuncs.com/test.jpg?x-oss-process=image/circle,r_100
先压缩再裁剪
http://demo.oss-cn-xxxxx.aliyuncs.com/test.jpg?x-oss-process=image/quality,q_80/circle,r_100