?說明:存在部分步驟省略的情況,請根據(jù)具體文檔進(jìn)行操作
?下載相關(guān)sdk
composer require qiniu/php-sdk
composer require aliyuncs/oss-sdk-php
composer require alibabacloud/sts-20150401
composer require qcloud/cos-sdk-v5
composer require qcloud_sts/qcloud-sts-sdk
# 如果不需要,請移除,示例:
# composer remove qcloud_sts/qcloud-sts-sdk
use Qiniu\Auth;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
require_once 'vendor/autoload.php'; // 請根據(jù)實(shí)際情況引入
class oss
{
public function qiniuPolicy()
{
$domain = ''; // 訪問oss文件的域名
$bucket = ''; // 空間名稱
$accessKey = '';
$secretKey = '';
$endpoint = ''; // 上傳文件的地址,例如:https://up-z2.qiniup.com
$prefix = ''; // 指定bucket目錄前綴
$dir = $prefix . '/' . date('Ymd') . '/'; // 按日期上傳到指定目錄
$expire = time() + 3600;
$policyArr = [
'scope' => $bucket,
'deadline' => $expire,
'fsizeMin' => 1,
'fsizeLimit' => 10 * 1024 * 1024,
];
$auth = new Auth($accessKey, $secretKey);
$token = $auth->uploadToken($bucket, null, 3600, $policyArr);
if (empty($token)) {
return [];
}
return [
'endpoint' => $endpoint,
'host' => $domain,
'accessId' => '',
'policy' => '',
'signature' => '',
'token' => $token,
'expire' => $expire,
'keyTime' => '',
'algorithm' => '',
'dir' => $dir,
];
}
public function aliPolicy()
{
// https://help.aliyun.com/zh/oss/use-cases/obtain-signature-information-from-the-server-and-upload-data-to-oss
$domain = ''; // 訪問oss文件的域名
$bucket = ''; // 空間名稱
$accessKey = '';
$secretKey = '';
$endpoint = ''; // 上傳文件的地址,例如:https://{bucket名稱}.oss-cn-shenzhen.aliyuncs.com
$prefix = ''; // 指定bucket目錄前綴
$dir = $prefix . '/' . date('Ymd') . '/'; // 按日期上傳到指定目錄
// https://help.aliyun.com/zh/oss/developer-reference/postobject#section-d5z-1ww-wdb
$expire = time() + 3600;
$policyArr = [
'expiration' => date('Y-m-d\TH:i:s.000\Z', $expire),
'conditions' => [
['bucket' => $bucket],
['content-length-range', 1, 10 * 1024 * 1024],
]
];
$policy = base64_encode(json_encode($policyArr));
// https://help.aliyun.com/zh/oss/developer-reference/postobject#section-wny-mww-wdb
$signature = base64_encode(hash_hmac('sha1', $policy, $secretKey, true));
return [
'endpoint' => $endpoint,
'host' => $domain,
'accessId' => $accessKey,
'policy' => $policy,
'signature' => $signature,
'token' => '',
'expire' => $expire,
'keyTime' => '',
'algorithm' => '',
'dir' => $dir,
];
}
public function aliSts()
{
// https://help.aliyun.com/zh/oss/developer-reference/authorize-access-2
try {
// 填寫步驟1創(chuàng)建的RAM用戶AccessKey。
$config = new Config([
"accessKeyId" => "【填寫】",
"accessKeySecret" => "【填寫】"
]);
//
$config->endpoint = "【填寫】"; // sts.cn-hangzhou.aliyuncs.com
$client = new Sts($config);
$assumeRoleRequest = new AssumeRoleRequest([
// roleArn填寫步驟2獲取的角色ARN,例如acs:ram::175708322470****:role/ramtest。
"roleArn" => "【填寫】",
// roleSessionName用于自定義角色會話名稱,用來區(qū)分不同的令牌,例如填寫為sessiontest。
"roleSessionName" => "【填寫】",
// durationSeconds用于設(shè)置臨時訪問憑證有效時間單位為秒,最小值為900,最大值以當(dāng)前角色設(shè)定的最大會話時間為準(zhǔn)。本示例指定有效時間為3000秒。
"durationSeconds" => 3000,
// policy填寫自定義權(quán)限策略,用于進(jìn)一步限制STS臨時訪問憑證的權(quán)限。如果不指定Policy,則返回的STS臨時訪問憑證默認(rèn)擁有指定角色的所有權(quán)限。
// 臨時訪問憑證最后獲得的權(quán)限是步驟4設(shè)置的角色權(quán)限和該P(yáng)olicy設(shè)置權(quán)限的交集。
// "policy" => ""
]);
$runtime = new RuntimeOptions([]);
$result = $client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
//printf("AccessKeyId:" . $result->body->credentials->accessKeyId. PHP_EOL);
//printf("AccessKeySecret:".$result->body->credentials->accessKeySecret.PHP_EOL);
//printf("Expiration:".$result->body->credentials->expiration.PHP_EOL);
//printf("SecurityToken:".$result->body->credentials->securityToken.PHP_EOL);
}catch (Exception $e){
// printf($e->getMessage() . PHP_EOL);
return [];
}
return $result;
}
public function qcloudPolicy()
{
// https://cloud.tencent.com/document/product/436/14690
$domain = ''; // 訪問oss文件的域名
$bucket = ''; // 空間名稱
$accessKey = '';
$secretKey = '';
$endpoint = ''; // 上傳文件的地址,例如:https://{bucket名稱}.cos.ap-guangzhou.myqcloud.com
$prefix = ''; // 指定bucket目錄前綴
$dir = $prefix . '/' . date('Ymd') . '/'; // 按日期上傳到指定目錄
$algorithm = 'sha1';
$startTime = time();
$endTime = time() + 3600;
$expiration = date('Y-m-d\TH:i:s.000\Z', $endTime);
$keyTime = implode(';', [$startTime, $endTime]);
$policyArr = [
'expiration' => $expiration,
'conditions' => [
['acl' => 'default'],
['bucket' => $bucket],
['q-sign-algorithm' => $algorithm],
['q-ak' => $secretId],
['q-sign-time' => $keyTime]
]
];
$policy = base64_encode(json_encode($policyArr));
$signKey = hash_hmac($algorithm, $keyTime, $secretKey);
$stringToSign = sha1(json_encode($policyArr));
$signature = hash_hmac($algorithm, $stringToSign, $signKey);
return [
'endpoint' => $endpoint,
'host' => $domain,
'accessId' => $secretId,
'policy' => $policy,
'signature' => $signature,
'token' => '',
'expire' => $endTime,
'keyTime' => $keyTime,
'algorithm' => $algorithm,
'dir' => $dir,
];
}
public function qcloudSts()
{
// https://cloud.tencent.com/document/product/436/14048
// https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/php/demo/sts_test.php
$domain = config('oss.qcloud_domain');
$bucket = config('oss.qcloud_bucket');
$secretId = config('oss.qcloud_access_key');
$secretKey = config('oss.qcloud_secret_key');
$endpoint = config('oss.qcloud_endpoint');
$prefix = config('oss.qcloud_bucket_key_prefix');
$dir = $prefix . '/' . date('Ymd') . '/';
$region = 'ap-guangzhou';
$sts = new \QCloud\COSSTS\Sts();
$config = array(
'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
'domain' => 'sts.tencentcloudapi.com', // 域名,非必須,默認(rèn)為 sts.tencentcloudapi.com
'proxy' => '',
'secretId' => $secretId, // 固定密鑰,若為明文密鑰,請直接以'xxx'形式填入,不要填寫到getenv()函數(shù)中
'secretKey' => $secretKey, // 固定密鑰,若為明文密鑰,請直接以'xxx'形式填入,不要填寫到getenv()函數(shù)中
'bucket' => $bucket, // 換成你的 bucket
'region' => $region, // 換成 bucket 所在園區(qū)
'durationSeconds' => 3600, // 密鑰有效期
'allowPrefix' => ['*'], // 這里改成允許的路徑前綴,可以根據(jù)自己網(wǎng)站的用戶登錄態(tài)判斷允許上傳的具體路徑,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全風(fēng)險(xiǎn), 請謹(jǐn)慎評估使用)
// 密鑰的權(quán)限列表。簡單上傳和分片需要以下的權(quán)限,其他權(quán)限列表請看 https://cloud.tencent.com/document/product/436/31923
'allowActions' => array(
// 簡單上傳
'name/cos:PutObject',
'name/cos:PostObject',
// 分片上傳
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload'
),
// 臨時密鑰生效條件,關(guān)于condition的詳細(xì)設(shè)置規(guī)則和COS支持的condition類型可以參考 https://cloud.tencent.com/document/product/436/71306
'condition' => []
);
// 獲取臨時密鑰,計(jì)算簽名
$tempKeys = $sts->getTempKeys($config);
return $tempKeys ?: [];
/**
數(shù)據(jù)如下:
{
"expiredTime": 1691169303,
"expiration": "2023-08-04T17:15:03Z",
"credentials": {
"sessionToken": "",
"tmpSecretId": "",
"tmpSecretKey": ""
},
"requestId": "6b274db5-a86b-4e27-a0e9-50f8ae1832f4",
"startTime": 1691165703
}
*/
}
}
表單提交到七牛云
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>七牛云oss upload</title>
</head>
<body>
<form method="post" action="{來自于$data里面的endpoint}" enctype="multipart/form-data">
<input type="hidden" name="key" id="key" value="">
<input type="hidden" name="token" id="token" value="">
<input type="hidden" name="crc32" />
<input type="hidden" name="accept" />
<input type="file" name="file" id="file" onchange="change(this)" />
<input type="submit" value="上傳文件" id="submit"/>
</form>
<script>
// 實(shí)例化oss類,獲取數(shù)據(jù)
// $oss = new oss();
// $data = $oss->qiniuPolicy();
let eleKey = document.getElementById('key');
let eleToken = document.getElementById('token');
eleToken.value = ''; // 來自$data里面的token
function change(obj) {
let uploadDir = ''; // 來自$data里面的dir
let fname = uploadDir + obj.files[0]['name'];
console.log(fname);
eleKey.value = fname;
}
</script>
</body>
</html>
表單提交到阿里云
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>阿里云oss upload</title>
</head>
<body>
<form method="post" action="{來自于$data里面的endpoint}" enctype="multipart/form-data">
<input type="hidden" name="key" id="key" value="">
<input type="hidden" name="OSSAccessKeyId" id="accessKey" value="">
<input type="hidden" name="policy" id="policy" value="">
<input type="hidden" name="signature" id="signature" value="">
<input name="file" type="file" id="file" onchange="change(this)" />
<input type="submit" value="上傳文件" id="submit"/>
</form>
<script>
// 實(shí)例化oss類,獲取數(shù)據(jù)
// $oss = new oss();
// $data = $oss->aliPolicy();
let eleKey = document.getElementById('key');
let eleAccessKey= document.getElementById('accessKey');
let elePolicy = document.getElementById('policy');
let eleSignature = document.getElementById('signature');
eleAccessKey.value = ''; // 來自$data里面的accessId
elePolicy.value = ''; // 來自$data里面的policy
eleSignature.value = ''; // 來自$data里面的signature
function change(obj) {
let uploadDir = ''; // 來自$data里面的dir
let fname = uploadDir + obj.files[0]['name'];
console.log(fname);
eleKey.value = fname;
}
</script>
</body>
</html>
?表單提交到阿里云(sts)
說明:需要修改acl權(quán)限,不然無法上傳文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>阿里云oss upload</title>
</head>
<body>
<input id="file" type="file" />
<button id="upload">上傳</button>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"></script>
<script>
// yourRegion填寫B(tài)ucket所在地域。以華東1(杭州)為例,yourRegion填寫為oss-cn-hangzhou。
let region = '';
// 填寫B(tài)ucket名稱。
let bucket = '';
// 從STS服務(wù)獲取的臨時訪問密鑰(AccessKey ID和AccessKey Secret)。
// 從STS服務(wù)獲取的安全令牌(SecurityToken)。
let stsData = {
AccessKeyId:"",
AccessKeySecret:"",
Expiration:"",
SecurityToken:""
};
const client = new OSS({
// yourRegion填寫B(tài)ucket所在地域。以華東1(杭州)為例,yourRegion填寫為oss-cn-hangzhou。
region: region,
// 從STS服務(wù)獲取的臨時訪問密鑰(AccessKey ID和AccessKey Secret)。
accessKeyId: stsData.AccessKeyId,
accessKeySecret: stsData.AccessKeySecret,
// 從STS服務(wù)獲取的安全令牌(SecurityToken)。
stsToken: stsData.SecurityToken,
// 填寫B(tài)ucket名稱。
bucket: bucket
});
// 從輸入框獲取file對象,例如<input type="file" id="file" />。
let data;
// 創(chuàng)建并填寫B(tài)lob數(shù)據(jù)。
//const data = new Blob(['Hello OSS']);
// 創(chuàng)建并填寫OSS Buffer內(nèi)容。
//const data = new OSS.Buffer(['Hello OSS']);
const upload = document.getElementById("upload");
async function putObject (data) {
try {
// 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
// 您可以通過自定義文件名(例如exampleobject.txt)或文件完整路徑(例如exampledir/exampleobject.txt)的形式實(shí)現(xiàn)將數(shù)據(jù)上傳到當(dāng)前Bucket或Bucket中的指定目錄。
// data對象可以自定義為file對象、Blob數(shù)據(jù)或者OSS Buffer。
const result = await client.put(
"1.png",
data
);
console.log(result);
} catch (e) {
console.log(e);
}
}
upload.addEventListener("click", () => {
const data = file.files[0];
putObject(data);
});
</script>
</body>
</html>
表單提交到騰訊云
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>騰訊云oss upload</title>
</head>
<body>
<form method="post" action="{來自于$data里面的endpoint}" enctype="multipart/form-data">
<input type="hidden" name="key" id="key" value="">
<input type="hidden" name="acl" id="acl" value="default">
<input type="hidden" name="policy" id="policy" value="">
<input type="hidden" name="q-sign-algorithm" id="algorithm" value="">
<input type="hidden" name="q-ak" id="ak" value="">
<input type="hidden" name="q-key-time" id="keyTime" value="">
<input type="hidden" name="q-signature" id="signature" value="">
<input type="file" name="file" id="file" onchange="change(this)" />
<input type="submit" value="上傳文件" id="submit"/>
</form>
<script>
// 實(shí)例化oss類,獲取數(shù)據(jù)
// $oss = new oss();
// $data = $oss->qcloudPolicy();
let eleKey = document.getElementById('key');
let elePolicy = document.getElementById('policy');
let eleAlgorithm = document.getElementById('algorithm');
let eleAK = document.getElementById('ak');
let eleKeyTime = document.getElementById('keyTime');
let eleSignature = document.getElementById('signature');
elePolicy.value = ''; // 來自$data里面的policy
eleAlgorithm.value = ''; // 來自$data里面的algorithm
eleAK.value = ''; // 來自$data里面的accessId
eleKeyTime.value = ''; // 來自$data里面的keyTime
eleSignature.value = ''; // 來自$data里面的signature
function change(obj) {
let uploadDir = ''; // 來自$data里面的dir
let fname = uploadDir + obj.files[0]['name'];
console.log(fname);
eleKey.value = fname;
}
</script>
</body>
</html>
表單提交到騰訊云(sts)?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>騰訊云oss upload</title>
</head>
<body>
<input type="file" name="file" id="file"/>
<input type="submit" value="上傳文件" id="submit"/>
<!-- 下載https://github.com/tencentyun/cos-js-sdk-v5/blob/master/dist/cos-js-sdk-v5.min.js,并引入cos-js-sdk-v5.min.js -->
<script src="./cos-js-sdk-v5.min.js"></script>
<!-- 詳見:https://cloud.tencent.com/document/product/436/11459 -->
<script>
var cos = new COS({
// getAuthorization 必選參數(shù)
getAuthorization: function (options, callback) {
// 異步獲取臨時密鑰
// 服務(wù)端 JS 和 PHP 例子:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
// 服務(wù)端其他語言參考 COS STS SDK :https://github.com/tencentyun/qcloud-cos-sts-sdk
// STS 詳細(xì)文檔指引看:https://cloud.tencent.com/document/product/436/14048
// 實(shí)例化oss類,獲取數(shù)據(jù)
// $oss = new oss();
// $data = $oss->qcloudSts();
// 服務(wù)端響應(yīng)的數(shù)據(jù),示例:
let data = {
"expiredTime": 1691382256,
"expiration": "2023-08-07T04:24:16Z",
"credentials": {
"sessionToken": "",
"tmpSecretId": "",
"tmpSecretKey": ""
},
"requestId": "",
"startTime": 1691378656
};
callback({
TmpSecretId: data.credentials.tmpSecretId,
TmpSecretKey: data.credentials.tmpSecretKey,
SecurityToken: data.credentials.sessionToken,
// 建議返回服務(wù)器時間作為簽名的開始時間,避免用戶瀏覽器本地時間偏差過大導(dǎo)致簽名錯誤
StartTime: data.startTime, // 時間戳,單位秒,如:1580000000
ExpiredTime: data.expiredTime, // 時間戳,單位秒,如:1580000000
});
}
});
function handleFileInUploading(file) {
cos.uploadFile({
Bucket: '【填寫】', /* 填寫自己的 bucket,必須字段 */
Region: '【填寫】', /* 存儲桶所在地域,必須字段 */
Key: file.name, /* 存儲在桶里的對象鍵(例如:1.jpg,a/b/test.txt,圖片.jpg)支持中文,必須字段 */
Body: file, // 上傳文件對象
SliceSize: 1024 * 1024 * 10, /* 觸發(fā)分塊上傳的閾值,超過5MB使用分塊上傳,小于5MB使用簡單上傳??勺孕性O(shè)置,非必須 */
onProgress: function (progressData) {
console.log(JSON.stringify(progressData));
}
}, function (err, data) {
if (err) {
console.log('上傳失敗', err);
} else {
console.log('上傳成功');
}
});
}
/* 選擇文件 */
document.getElementById('submit').onclick = function (e) {
var file = document.getElementById('file').files[0];
if (!file) {
document.getElementById('msg').innerText = '未選擇上傳文件';
return;
}
handleFileInUploading(file);
};
</script>
</body>
</html>
參考:
?上傳策略_使用指南_對象存儲 - 七牛開發(fā)者中心
上傳憑證_使用指南_對象存儲 - 七牛開發(fā)者中心
如何進(jìn)行服務(wù)端簽名直傳_對象存儲-阿里云幫助中心
如何使用STS以及簽名URL臨時授權(quán)訪問OSS資源(PHP)_對象存儲-阿里云幫助中心
對象存儲 Web 端直傳實(shí)踐-最佳實(shí)踐-文檔中心-騰訊云
對象存儲 POST Object-API 文檔-文檔中心-騰訊云
對象存儲 臨時密鑰生成及使用指引-最佳實(shí)踐-文檔中心-騰訊云文章來源:http://www.zghlxwxcb.cn/news/detail-628267.html
對象存儲 快速入門-SDK 文檔-文檔中心-騰訊云文章來源地址http://www.zghlxwxcb.cn/news/detail-628267.html
到了這里,關(guān)于使用七牛云、阿里云、騰訊云的對象存儲上傳文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!