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

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

 下载相关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.mzph.cn/news/22647.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Centos时间同步

前言 在 Linux 操作系统中&#xff0c;正确的时间同步是非常重要的&#xff0c;因为它对于很多应用程序都是必需的。本文将介绍两种在 Centos 系统中同步当前时间的方式。 方法一&#xff1a;使用 ntpdate 命令同步当前时间 ntpdate 命令是一种简单快捷的同步当前时间的方式&a…

两个镜头、视野、分辨率不同的相机(rgb、红外)的视野校正

文章目录 背景实际效果查找资料资料1资料2 解决方案最终结果 背景 目前在做的项目用到两个摄像头&#xff0c;一个是热成像摄像头、另一个是普通的rgb摄像头。 一开始的目标是让他们像素级重合&#xff0c;使得点击rgb图像时&#xff0c;即可知道其像素对应的温度。但是在尝试…

物理机是什么?有什么优势?可以上堡垒机吗?

你知道物理机是什么&#xff1f;有什么优势&#xff1f;可以上堡垒机吗&#xff1f;今天我们就来简单聊聊。 物理机是什么&#xff1f; 物理机是相对于虚拟机而言的对实体计算机的称呼。物理机提供给虚拟机以硬件环境&#xff0c;有时也称为“寄主”或“宿主”。 物理机有什么…

docker compose一键部署lnmt环境

创建docker compose 目录 [rootlocalhost ~]# mkdir -p /compose_lnmt 编写nginx的dockerfile文件 创建目录 [rootlocalhost compose_lnmt]# mkdir -p nginx 编写nginx配置文件 [rootlocalhost nginx]# vim nginx.conf user root; #运行身份#nginx自动设置进程…

web基础与tomcat环境部署

一. 简述静态网页和动态网页的区别。 请求响应信息&#xff0c;发给客户端进行处理&#xff0c;由浏览器进行解析&#xff0c;显示的页面称为静态页面。处理文件类型如.html、jpg、.gif、.mp4、.swf、.avi、.wmv、.flv等 请求响应信息&#xff0c;发给事务端进行处理&#xff0…

红帽8.2版本CSA题库:第一题配置网络设置

红帽认证工程师是业界公认的最权威的Linux认证之一。RHCE 是世界上第一个面向Linux 的认证考试&#xff0c;它不是一个普通的认证测试&#xff0c;和其他操作系统认证考试相比&#xff0c;它没有笔试&#xff0c;全部是现场实际操作&#xff0c;所以RHCE成了业界公认的最难的认…

【Java基础教程】(四十四)IO篇 · 上:File类、字节流与字符流,分析字节输出流、字节输入流、字符输出流和字符输入流的区别~

Java基础教程之IO操作 上 &#x1f539;本节学习目标1️⃣ 文件操作类&#xff1a;File2️⃣ 字节流与字符流2.1 字节输出流&#xff1a;OutputStream2.2 字节输入流&#xff1a;InputStream2.3 字符输出流&#xff1a;Writer2.4 字符输入流&#xff1a;Reader2.5 字节流与字符…

router-view路由出口

这边文章主要讲router-view搭建后台管理系统的一个基本模板 一.创建自己的路由规则 1.新建文件夹src/router/index.js npm i vue-router3.6.5 2.配置好文件 import Vue from "vue"; import VueRouter from "vue-router"; Vue.use(VueRouter);// 1.创建…

俄罗斯方块

俄罗斯方块简单实现 使用 pygame 模块实现俄罗斯方块的简单实现&#xff0c;这里没有使用pygame 自带的碰撞检测&#xff0c;而是自定义的方法实现边界碰撞和方块间碰撞检测。 代码实现 import random import pygame import time # 初始化游戏 pygame.init()# 设置游戏窗口大…

C#中Convert.ToInt32() 和 int.Parse()的区别

都是用于将字符串转换为整数类型&#xff08;int&#xff09;的方法&#xff0c;但它们在处理转换过程中有一些区别&#xff1a; 1. 错误处理方式不同&#xff1a; - Convert.ToInt32()&#xff1a;如果字符串无法成功转换为整数类型&#xff0c;Convert.ToInt32()…

python整型和浮点型

在Python中&#xff0c;浮点数是一种用于表示带有小数部分的数值类型。浮点数可以用来进行各种数学运算&#xff0c;包括加法、减法、乘法和除法等。 以下是Python中使用浮点数的语法示例&#xff1a; # 声明一个浮点数变量number 3.14# 进行浮点数之间的运算a 2.5b 1.3c a…

使用AIGC工具提升安全工作效率

新钛云服已累计为您分享760篇技术干货 在日常工作中&#xff0c;安全人员可能会涉及各种各样的安全任务&#xff0c;包括但不限于&#xff1a; 开发某些安全工具的插件&#xff0c;满足自己特定的安全需求&#xff1b;自定义github搜索工具&#xff0c;快速查找所需的安全资料、…

AI大模型的现状与发展

文章目录 方向一&#xff1a;“反AI斗士”马斯克进军AI&#xff0c;你怎么看&#xff1f;方向二&#xff1a;回顾上半年的“百模大战”&#xff0c;中国的AI产业怎么样了&#xff1f;方向三&#xff1a;AI大模型这把火&#xff0c;还能怎么烧&#xff1f; 北京时间7月13日凌晨&…

Python(六十七)什么是元组

❤️ 专栏简介&#xff1a;本专栏记录了我个人从零开始学习Python编程的过程。在这个专栏中&#xff0c;我将分享我在学习Python的过程中的学习笔记、学习路线以及各个知识点。 ☀️ 专栏适用人群 &#xff1a;本专栏适用于希望学习Python编程的初学者和有一定编程基础的人。无…

Python脚本-时间盲注

BlindBool_get import requests from optparse import OptionParser import threading#存放变量 DBName "" DBTables [] DBColumns [] DBData {} flag You are in #设置重连次数以及将连接改为短连接 #防止因为HTTP连接数过多导致的MAX retries exceeded with …

【Linux后端服务器开发】Reactor模式实现网络计算器

目录 一、Reactor模式概述 二、日志模块&#xff1a;Log.hpp 三、TCP连接模块&#xff1a;Sock.hpp 四、非阻塞通信模块&#xff1a;Util.hpp 五、多路复用I/O模块&#xff1a;Epoller.hpp 六、协议定制模块&#xff1a;Protocol.hpp 七、服务器模块&#xff1a;Server.…

MySQL安装详细教程!!!

安装之前&#xff0c;先卸载你之前安装过的数据库程序&#xff0c;否则会造成端口号占用的情况。 1.首先下载MySQL:MySQL :: Download MySQL Community Server(下载路径) 2.下载版本不一样&#xff0c;安装方法略有不同&#xff1b;&#xff08;版本5的安装基本一致&#xff0c…

gitlab搭建

回到目录 GitLab 是一个用于仓库管理系统的开源项目&#xff0c;使用 Git 作为代码管理工具&#xff0c;并在此基础上搭建起来的 Web 服务。 Gitlab 是被广泛使用的基于 git 的开源代码管理平台, 基于 Ruby on Rails 构建, 主要针对软件开发过程中产生的代码和文档进行管理,…

六、目录树生成工具_zDirTree

1、zDirTree工具简介 zDirTree可以根据文件资源生成目录树&#xff0c;就是用文本的形式把文件层级结构表示出来&#xff0c;可以方便理解文件结构。 2、zDirTree工具下载 (1)我没有找到这工具的官方下载地址。 (2)我是微信公众号"干货食堂"中下载。 3、软件使用…

健身计划:用思维导图记录你的健身目标、锻炼项目、时间安排等

现在&#xff0c;大家越来越在乎自己的身体健康&#xff0c;健身也成了大家工作之外非常重要的一件事。一个好的健身计划的制定可以让我们的健身计划事半功倍。 思维导图作为一种高效的可视化思维工具&#xff0c;在健身计划制定的过程中&#xff0c;可以让我们的各项任务与时间…