Thinkphp5 集成阿里云OSS
------安装阿里云OSS SDK -----
composer require aliyuncs/oss-sdk-php
------配置阿里云设置-- tp根目录/application/config.php------
'alioss' => [ 'acckeyid' => 'LTAI4Fqono2Jc1LBjMcB****', //keyid 'acckeysecret' => 'LYsINIwfRjVHu60aC1NGYXm4r****', //keysecret 'endpoint' => 'http://ddddmehlhlyou-test-aliyunoss.xiaoguan.net', //外网域名,自定义域名 - 必须绑定备案的域名否则会自动下载 'bucket' => 'ddddmehlhlyou-test', //bucket名称 'custom' => 'true', //是否自定义域名 ]
------通用API方法封装 -- tp根目录/application/extra/api.php------
<?php
// +----------------------------------------------------------------------
// | 通用方法
// +----------------------------------------------------------------------
use OSS\OssClient;
use OSS\Core\OssException;
class API
{
//上传实例化
public static function uploadOSS($filename, $filebase){
$alioss = config('alioss');
// 上传时可以设置相关的headers,例如设置访问权限为private和自定义元信息。
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-object-acl' => 'private',
'x-oss-meta-info' => 'jonyguan-test'
),
);
try {
$newoss = new OssClient($alioss['acckeyid'], $alioss['acckeysecret'], $alioss['endpoint'], $alioss['custom']);
} catch (OssException $e) {
return $e->getMessage();
}
try {
$newoss->putObject($alioss['bucket'], $filename, $filebase, $options);
} catch (OssException $e) {
return $e->getMessage();
}
$imgUrl = $alioss['endpoint'] . '/' . $filename;
return $imgUrl;
}
//上传图片操作
public static function uploadImage($upfile){
$filebase = file_get_contents($upfile['tmp_name']);
$name = $upfile['name'];
$format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
/*判断图片格式*/
$allow_type = ['.jpg', '.jpeg', '.gif', '.png'];
if (!in_array($format, $allow_type)) {
API::ApiRes(0, "文件格式不在允许范围内哦");
}
$nowtime = time();
$today = date("Y-m-d",$nowtime);
$saveName = md5($nowtime . rand(000,999));
$filename = $today . '/' . $saveName.$format;
return self::uploadOSS($filename, $filebase);
}
}----控制器里调用--tp根目录/application/index/controller/index.php-----
use API;
public function upimg()
{
$upfile = $_FILES['image'];
$upimg = API::uploadImage($upfile);
var_dump($upimg);
}----路由配置-tp根目录/application/route.php-----
<?php
use think\Route;
Route::post('upimg','index/Index/upimg');----上传文件HTML---tp根目录/public/test.html----------访问此文件 http://localhost/test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>tp5-aliyunoss上传实例</title> </head> <body> <form action="/upimg" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit"> </form> </body> </html>