building-sign/app/service/Qiniu.php

79 lines
2.0 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace app\service;
use think\facade\Config;
use think\facade\Log;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Qiniu
{
private static $oss = null;
private function __construct()
{
}
private function __clone()
{
}
/**
* 七牛云OSS
*
*/
public static function config()
{
Config::load('extra/qiniu', 'qiniu');
return config('qiniu');
}
// 七牛云OSS实例 单例模式
public static function instance(): ?OssClient
{
if (self::$oss == null) {
try {
$conf = self::config();
self::$oss = new OssClient($conf['accessKeyId'], $conf['accessKeySecret'], $conf['endpoint']);
} catch (OssException $e) {
Log::error('实例化阿里云OSS失败: ' . $e->getMessage());
return null;
}
}
return self::$oss;
}
public static function aa()
{
$conf = self::config();
// 控制台获取密钥https://portal.qiniu.com/user/key
$accessKey = $conf['qiniuAccessKey'];
$secretKey = getenv('qiniuSecretKey');
$bucket = getenv('bucket');
// 构建鉴权对象
$auth = new Auth($accessKey, $secretKey);
// 生成上传 Token
$token = $auth->uploadToken($bucket);
// 要上传文件的本地路径
$filePath = './php-logo.png';
// 上传到七牛存储后保存的文件名
$key = 'my-php-logo.png';
// 初始化 UploadManager 对象并进行文件的上传。
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传,该方法会判断文件大小,进而决定使用表单上传还是分片上传,无需手动配置。
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
echo "\n====> putFile result: \n";
if ($err !== null) {
var_dump($err);
} else {
var_dump($ret);
}
}
}