当前位置: 首页 > news >正文

thinkcmf改存储CloudflareR2

先建一个服务类

<?php namespace app\portal\service; class CloudflareR2 { private $accessKey="42098b06dbxxxxxxxx48fad96f4f"; private $secretKey="02d3f18c4ac204d35xxxxxxxxxxxx73bcab3e4c01c982b16fe56c7a7951"; private $accountId="e94bae5daxxxxxx3abbd269e5e"; private $bucketName="suxxxxxoda"; private $region="auto"; public function __construct() { } /** * 获取存储桶 URL */ public function getBucketUrl() { return "{$this->accountId}.r2.cloudflarestorage.com/{$this->bucketName}"; } /** * 上传文件到 Cloudflare R2 */ public function uploadFile($filePath, $objectKey) { if (!file_exists($filePath)) { return ['success' => false, 'error' => 'File not found']; } // 使用同一个时间戳确保所有日期一致 $now = time(); $amzDate = gmdate('Ymd\THis\Z', $now); $dateStamp = gmdate('Ymd', $now); $fileSize = filesize($filePath); $contentType = mime_content_type($filePath); $fileContent = file_get_contents($filePath); // 1. 创建规范请求 $canonicalHeaders = [ 'content-length' => $fileSize, 'content-type' => $contentType, 'host' => "{$this->accountId}.r2.cloudflarestorage.com", 'x-amz-content-sha256' => hash('sha256', $fileContent), 'x-amz-date' => $amzDate ]; // 按字母顺序排序头 ksort($canonicalHeaders); $signedHeaders = implode(';', array_map('strtolower', array_keys($canonicalHeaders))); $canonicalRequest = "PUT\n" . '/' . $this->bucketName . '/' . str_replace('%2F', '/', rawurlencode($objectKey)) . "\n" . "\n" . implode("\n", array_map(function($k, $v) { return strtolower($k) . ':' . $v; }, array_keys($canonicalHeaders), $canonicalHeaders)) . "\n" . "\n" . $signedHeaders . "\n" . $canonicalHeaders['x-amz-content-sha256']; // 2. 创建待签字符串 $algorithm = "AWS4-HMAC-SHA256"; $credentialScope = "{$dateStamp}/{$this->region}/s3/aws4_request"; $stringToSign = "{$algorithm}\n{$amzDate}\n{$credentialScope}\n" . hash('sha256', $canonicalRequest); // 3. 计算签名 $signingKey = $this->getSignatureKey($dateStamp); $signature = hash_hmac('sha256', $stringToSign, $signingKey); // 4. 构建授权头 $authorizationHeader = "{$algorithm} " . "Credential={$this->accessKey}/{$credentialScope}, " . "SignedHeaders={$signedHeaders}, " . "Signature={$signature}"; // 5. 构造请求URL和头 $url = "https://{$this->accountId}.r2.cloudflarestorage.com/{$this->bucketName}/" . rawurlencode($objectKey); $headers = [ "Authorization: {$authorizationHeader}", "Content-Length: {$fileSize}", "Content-Type: {$contentType}", "Host: {$this->accountId}.r2.cloudflarestorage.com", "x-amz-content-sha256: {$canonicalHeaders['x-amz-content-sha256']}", "x-amz-date: {$amzDate}" ]; // 6. 发送请求 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //var_dump($response); die(); curl_close($ch); if ($httpCode === 200) { $url2 = env('CLOUDFLARE_URL') . rawurlencode($objectKey); return ['success' => true, 'url' => $url2]; } else { return [ 'success' => false, 'error' => 'Upload failed', 'http_code' => $httpCode, 'response' => $response, 'debug' => [ 'canonicalRequest' => $canonicalRequest, 'stringToSign' => $stringToSign, 'signingKey' => bin2hex($this->getSignatureKey($dateStamp)), 'signature' => $signature, 'headers' => $headers ] ]; } } /** * 生成签名密钥 */ private function getSignatureKey($dateStamp) { $kSecret = 'AWS4' . $this->secretKey; $kDate = hash_hmac('sha256', $dateStamp, $kSecret, true); $kRegion = hash_hmac('sha256', $this->region, $kDate, true); $kService = hash_hmac('sha256', 's3', $kRegion, true); $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true); return $kSigning; } }

再来个调用的

<?php namespace app\portal\service; use cmf\lib\Storage; class CloudflareR2Storage extends Storage { /** * 上传文件到 Cloudflare R2 * @param string $file 文件路径 * @param string $filePath 本地文件路径 * @param string $fileType 文件类型 * @param array $param 其他参数 * @return array|bool */ public function upload($file, $filePath, $fileType = 'image', $param = null) { $cloudflareR2 = new CloudflareR2(); $objectKey = ltrim($file, '/'); $result = $cloudflareR2->uploadFile($filePath, $objectKey); if ($result['success']) { // 删除本地文件 // @unlink($filePath); return [ 'preview_url' => $result['url'], 'url' => $result['url'], ]; } else { return false; } } /** * 获取图片预览 URL * @param string $file * @param string $style * @return mixed */ public function getPreviewUrl($file, $style = '') { return "https://" . (new CloudflareR2())->getBucketUrl() . "/" . ltrim($file, '/'); } /** * 获取图片 URL * @param string $file * @param string $style * @return mixed */ public function getImageUrl($file, $style = '') { return "https://" . (new CloudflareR2())->getBucketUrl() . "/" . ltrim($file, '/'); } /** * 获取文件下载 URL * @param string $file * @param int $expires * @return mixed|string */ public function getFileDownloadUrl($file, $expires = 3600) { return "https://" . (new CloudflareR2())->getBucketUrl() . "/" . ltrim($file, '/'); } }

然后找到cmf的扩展,找到对应的上传方法

在他上传的方法前面插入个自己的上传判断

// 检查是否配置了 Cloudflare R2 存储 $storage = cmf_get_option('storage'); if ( env('CLOUDFLARE_STATUS') == 1) { // 使用 Cloudflare R2 存储 $cloudflareR2Storage = new \app\portal\service\CloudflareR2Storage(); $result = $cloudflareR2Storage->upload($arrInfo["file_path"], $uploadPath . $arrInfo["file_path"], $fileType); if ($result) { // 删除本地文件 // @unlink($uploadPath . $arrInfo["file_path"]); return array_merge([ 'filepath' => $arrInfo["file_path"], "name" => $arrInfo["filename"], 'id' => $strId, 'preview_url' => $result['preview_url'], 'url' => $result['url'], ], $result); } }

我是直接写在配置文件读取的,要不要写数据库看自己了.

这样就能实现上传到Cloundflare,接着还要处理回显的问题.找到这函数

,改写他

function cmf_get_image_url($file, $style = 'watermark') { if (empty($file)) { return ''; } if (strpos($file, "http") === 0) { return $file; } else { // 获取云存储配置 $CLOUDFLARE_STATUS = env("CLOUDFLARE_STATUS"); $cloudStorageUrl = env("CLOUDFLARE_URL"); // 如果配置了云存储URL,则直接使用 if ($CLOUDFLARE_STATUS == 1) { // 处理路径 $file = ltrim(str_replace('\\', '/', $file), '/'); //如果不是thems开头的需要加上upload前缀 // if (!preg_match('/^themes/', $file) && !preg_match('/^static/', $file)) { // $file = 'upload/' . $file; // } return rtrim($cloudStorageUrl, '/') . '/' . $file; } else { // 使用默认的存储处理 $storage = Storage::instance(); return $storage->getImageUrl($file, $style); } } }

具体匹配规则看自己实际目录结构了.

这样就完成了上传到Cloudflare.

http://www.cnnetsun.cn/news/40495.html

相关文章:

  • 柠檬 软件测试之python全栈自动化测试工程师第25期
  • 为什么你的视觉AI项目总是耗时又低效?Florence-2-large-ft一站式解决方案
  • 基于php的微信小程序的学习交流平台系统(源码+lw+部署文档+讲解等)
  • springboot高校读书分享系统的设计与实现_34ur7fyk-
  • 如何快速解锁RouterOS无限权限:MikroTikPatch的终极指南
  • 测试工程师的增值型职业休假策略:从技术深耕到跨界突破
  • USART串口
  • SDET职业生涯中的关键决策点与路径选择
  • 第三方API密集型聚合服务的测试体系构建
  • System Informer:你的Windows系统管家,3大核心功能深度解析
  • 探索城市脉搏:解密共享单车数据背后的故事
  • 如何用abogen构建高质量有声书生成系统:从单文件到批量处理的完整指南
  • FastText实战进阶:解锁文本处理的极致性能与多场景应用
  • 车载功能测试都要做什么?总结来了~
  • 终极指南:掌握CogVLM多模态大模型核心技术
  • 【毕业设计/课程设计】基于Python的热门微博数据可视化分析源码+论文+PPT+数据
  • 监控选购全攻略:6大场景首选品牌,海康威视/格行视精灵各有侧重,小米性价比,萤石更全能;格行视精灵AOV技术+终生免流真好用?
  • 5步掌握Three.js延迟渲染技术:从多光源卡顿到流畅渲染的终极指南
  • Profinet转ModbusTCP网关:实现西门子1200PLC与打标卡稳定通讯
  • 工业设备实现全远程化运维的意义在哪
  • Signal-Android终极优化指南:7步实现APK大小缩减50%
  • TUnit集成WireMock:构建稳定可靠的.NET测试体系
  • 2025三季度报告出炉,平安银行存款平稳运行付息率降本增效
  • 掌握问题解决的艺术:波利亚《怎样解题》思维训练指南
  • 终极指南:如何快速上手MDPI Electronics论文LaTeX模板?
  • 已验证!零基础转行网络安全,我亲身实践的半年高效学习路线与复盘
  • 想从零转行网络安全?这是给你的入门指南与必须知道的避坑要点
  • High Performance Computing Center North(HPC2N),瑞典超算中心
  • VMnet没有未桥接的主机网络适配器
  • NVIDIA开源GPU内核模块完全掌握:从架构解析到高效部署实战