使用七牛云、阿里云、腾讯云的对象存储上传文件

news/2025/1/12 19:58:38/

 说明:存在部分步骤省略的情况,请根据具体文档进行操作

 下载相关sdk

composer require qiniu/php-sdkcomposer require aliyuncs/oss-sdk-php
composer require alibabacloud/sts-20150401composer 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 __DIR__ . 'vendor/autoload.php';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-2try {// 填写步骤1创建的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用于自定义角色会话名称,用来区分不同的令牌,例如填写为sessiontest。"roleSessionName" => "【填写】",// durationSeconds用于设置临时访问凭证有效时间单位为秒,最小值为900,最大值以当前角色设定的最大会话时间为准。本示例指定有效时间为3000秒。"durationSeconds" => 3000,// policy填写自定义权限策略,用于进一步限制STS临时访问凭证的权限。如果不指定Policy,则返回的STS临时访问凭证默认拥有指定角色的所有权限。// 临时访问凭证最后获得的权限是步骤4设置的角色权限和该Policy设置权限的交集。// "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', // 域名,非必须,默认为 sts.tencentcloudapi.com'proxy' => '','secretId' => $secretId, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中'secretKey' => $secretKey, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中'bucket' => $bucket, // 换成你的 bucket'region' => $region, // 换成 bucket 所在园区'durationSeconds' => 3600, // 密钥有效期'allowPrefix' => ['*'], // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)// 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 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'),// 临时密钥生效条件,关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306'condition' => []);// 获取临时密钥,计算签名$tempKeys = $sts->getTempKeys($config);return $tempKeys ?: [];/**
数据如下:
{"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>// 实例化oss类,获取数据// $oss = new oss();// $data = $oss->qiniuPolicy();let eleKey = document.getElementById('key');let eleToken = document.getElementById('token');eleToken.value = ''; // 来自$data里面的tokenfunction change(obj) {let uploadDir = ''; // 来自$data里面的dirlet 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>// 实例化oss类,获取数据// $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里面的accessIdelePolicy.value = ''; // 来自$data里面的policyeleSignature.value = ''; // 来自$data里面的signaturefunction change(obj) {let uploadDir = ''; // 来自$data里面的dirlet 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 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填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。let region = '';// 填写Bucket名称。let bucket = '';// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。// 从STS服务获取的安全令牌(SecurityToken)。let stsData = {AccessKeyId:"",AccessKeySecret:"",Expiration:"",SecurityToken:""};const client = new OSS({// yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。region: region,// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。accessKeyId: stsData.AccessKeyId,accessKeySecret: stsData.AccessKeySecret,// 从STS服务获取的安全令牌(SecurityToken)。stsToken: stsData.SecurityToken,// 填写Bucket名称。bucket: bucket});// 从输入框获取file对象,例如<input type="file" id="file" />。let data;// 创建并填写Blob数据。//const data = new Blob(['Hello OSS']);// 创建并填写OSS Buffer内容。//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)的形式实现将数据上传到当前Bucket或Bucket中的指定目录。// data对象可以自定义为file对象、Blob数据或者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>// 实例化oss类,获取数据// $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里面的policyeleAlgorithm.value = ''; // 来自$data里面的algorithmeleAK.value = ''; // 来自$data里面的accessIdeleKeyTime.value = ''; // 来自$data里面的keyTimeeleSignature.value = ''; // 来自$data里面的signaturefunction change(obj) {let uploadDir = ''; // 来自$data里面的dirlet 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>
<form method="post" action="https://test-1312063917.cos.ap-guangzhou.myqcloud.com" enctype="multipart/form-data"><input type="hidden" name="x-cos-security-token" id="token" value=""><input type="hidden" name="key" id="key" value=""><input type="file" name="file" id="file" onchange="change(this)" /><input type="submit" value="上传文件" id="submit"/>
</form>
<script>// 实例化oss类,获取数据// $oss = new oss();// $data = $oss->qcloudSts();let eleKey = document.getElementById('key');let eleToken = document.getElementById('token');eleToken.value = ''; // $data['credentials']['sessionToken']function change(obj) {let uploadDir = ''; // 来自$data里面的dirlet fname = uploadDir + obj.files[0]['name'];console.log(fname);eleKey.value = fname;}
</script>
</body>
</html>


http://www.ppmy.cn/news/1008855.html

相关文章

Redis | 主从模式

Redis | 主从模式 1. 简介 Redis主从模式&#xff08;Replication&#xff09;是Redis提供的一种数据备份和高可用性解决方案。通过主从复制&#xff0c;可以将一个Redis服务器的数据复制到其他多个从服务器&#xff0c;从而实现数据的备份和读写分离&#xff0c;提高系统的性…

Spring Boot读取yml或者properties配置信息

文章目录 Spring Boot读取yml或者properties配置信息方法一&#xff1a;Value获取基本信息&#xff0c;适用于少量信息方法二&#xff1a;通过注解ConfigurationProperties(prefix "spring.datasource")方法三&#xff1a;通过api Environment Spring Boot读取yml或…

Android查漏补缺

&#xff08;1&#xff09;android apk编译步骤 ①&#xff0c;aapt工具生成.R文件 ②&#xff0c;javac编译为字节码 ③&#xff0c;dex工具打包为.dex文件 ④&#xff0c;aapt工具打包资源未见为.ap文件 ⑤&#xff0c;apkbuilder工具打包为apk文件 ⑥&#xff0c;keyt…

Linux 内核音频数据传递主要流程

Linux 用户空间应用程序通过声卡驱动程序&#xff08;一般牵涉到多个设备驱动程序&#xff09;和 Linux 内核 ALSA 框架导出的 PCM 设备文件&#xff0c;如 /dev/snd/pcmC0D0c 和 /dev/snd/pcmC0D0p 等&#xff0c;与 Linux 内核音频设备驱动程序和音频硬件进行数据传递。PCM 设…

2.文件的逻辑结构

第四章 文件管理 2.文件的逻辑结构 顺序文件采用顺序存储则意味着各个逻辑上相邻的记录在物理上也是相邻的存储的。所以如果第0号记录的逻辑地址为0的话&#xff0c;则i号记录的逻辑为i *L。 特别的如果这个定长记录的顺序文件采用串结构&#xff0c;也就是这些记录的顺序和他…

Go For Web:Golang http 包详解(源码剖析)

正文&#xff1a; Golang http 包详解&#xff08;源码剖析&#xff09; 前面小节我们认识了 Web 的工作方式&#xff0c;也成功用 Go 搭建了一个最简单的 Web 服务了解了 Golang 运行 Web 的原理。现在我们详细地去解剖以下 http 包&#xff0c;看看它如何实现整个过程的 Go…

识jvm堆栈中一个数据类型是否为为引用类型,目前虚拟机实现中是如何做的?

调用栈里的引用类型数据是GC的根集合&#xff08;root set&#xff09;的重要组成部分&#xff1b;找出栈上的引用是GC的根枚举&#xff08;root enumeration&#xff09;中不可或缺的一环。 要看JVM选择用什么方式。通常这个选择会影响到GC的实现。 如果JVM选择不记录任何这种…

CISCO MDS 9148 SAN Switch 交换机命令配置方法:

前言 CISCO MDS 9148 SAN 交换机已经停产&#xff0c;但还是要掌握一下配置的方法&#xff1a; 升级款后面 9148S 或者 9100系列&#xff0c;但配置方式基本都差不多&#xff0c;掌握一个就好&#xff1a; 高性能和极具吸引力的价值 Cisco MDS 9148S 16G 多层光纤交换机是下…