1. 程式人生 > 其它 >thinkphp6 上傳檔案到阿里雲oss

thinkphp6 上傳檔案到阿里雲oss

composer安裝
在專案的根目錄執行composer require aliyuncs/oss-sdk-php

git地址 https://github.com/aliyun/aliyun-oss-php-sdk

filesystem裡面配置:

// 更多的磁碟配置資訊
'aliyun' => [
'type' => 'aliyun',
'accessId' => '',
'accessSecret' => '',
'bucket' => '',
'endpoint' => '',// 節點
'url' => 'http://xxxxx',//不要斜槓結尾,此處為URL地址域名。
],

直接上程式碼:

    /*
* 圖片上傳,將圖片上傳至阿里雲oss
* */
public function uploads(){
$files = $_FILES['file'];
$name = $files['name'];
$format = strrchr($name, '.');//擷取檔案字尾名如 (.jpg)
// 阿里雲主賬號AccessKey擁有所有API的訪問許可權,風險很高。強烈建議您建立並使用RAM賬號進行API訪問或日常運維,請登入RAM控制檯建立RAM賬號。
$accessKeyId = Filesystem::getDiskConfig('aliyun', 'accessId');
$accessKeySecret = Filesystem::getDiskConfig('aliyun', 'accessSecret');
// Endpoint以杭州為例,其它Region請按實際情況填寫。
$endpoint = Filesystem::getDiskConfig('aliyun', 'endpoint');
// 設定儲存空間名稱。
$bucket= Filesystem::getDiskConfig('aliyun', 'bucket');
// 設定檔名稱。
//這裡是由sha1加密生成檔名 之後連線上檔案字尾,生成檔案規則根據自己喜好,也可以用md5
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
$path = 'qialiao/ios/';
}else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android')){
$path = 'qialiao/android/';
}else{
$path = 'qialiao/other/';
}
//前面video/head/ 這是我的oss目錄
$object = $path.sha1(date('YmdHis', time()) . uniqid()) . $format;;
// <yourLocalFile>由本地檔案路徑加檔名包括字尾組成,例如/users/local/myfile.txt。
$filePath = $files['tmp_name'];
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

$result = $ossClient->uploadFile($bucket, $object, $filePath);
if(!$result){
return json_data([],400,'上傳失敗');
}else{
$data['src'] = $result['info']['url'];
return json_data($data);
}
} catch(OssException $e) {
// printf(__FUNCTION__ . ": FAILED\n");
// printf($e->getMessage() . "\n");
return json_data([],400,$e->getMessage());
}
// print(__FUNCTION__ . ": OK" . "\n");
}

$result['info']['url']是oss圖片地址