环境:tp8\php8.3; 服务器:centOS Stream 9;
场景:通过html页面直传七牛云服务器,速度更快;
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>图片上传</title>
</head>
<body>
<form method="post" action="https://up-z1.qiniup.com" enctype="multipart/form-data"><input name="key" type="hidden" value="{$key}"><input name="x:classID" type="hidden" value="2"><input name="x:smallclassID" type="hidden" value="6"><input name="x:userId" type="hidden" value="1"><input name="x:orderNum" type="hidden" value="202507021320123"><input name="token" type="hidden" value="{$token}"><input name="file" type="file" /><input type="submit" value="上传文件" />
</form>
</body>
</html>
action地址自己查看七牛云后台,查看存储桶所在的地区;文档一定要仔细看;
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;use think\facade\Log;class Demo
{public function getToken(){// 控制台获取密钥:https://portal.qiniu.com/user/key$accessKey ="";$secretKey = "";$bucket = "";// 初始化 Auth 状态$auth = new Auth($accessKey, $secretKey);// 带回调业务服务器的凭证(application/json)$expires = 3600;$startTime = time(); // 当前时间戳$newTimestamp = $startTime + 3600; // 加 3600 秒$key = '2005/'.time().'.jpg';$policy = array('scope'=>$key,'deadline'=>$newTimestamp,'callbackUrl' => 'https://api.yourdomain.com/index/demo/callback','callbackBody' => '{"key":"$(key)","bucket":"$(bucket)","classID":"$(x:classID)","smallclassID":"$(x:smallclassID)","userId":"$(x:userId)","orderNum":"$(x:orderNum)"}','callbackBodyType' => 'application/json');$upToken = $auth->uploadToken($bucket, null, $expires, $policy, true);// print($upToken . "\n");return view('/demo',['token'=>$upToken,'key'=>$key]);}public function callback(){// 获取七牛云回调的 JSON 数据$key = input('post.key');$bucket = input('post.bucket');$classID = input('post.classID');$smallclassID = input('post.smallclassID');$userId = input('post.userId');$orderNum = input('post.orderNum');$data = ['key'=>$key,'bucket'=>$bucket,'classID'=>$classID,'smallclassID'=>$smallclassID,'userId'=>$userId,'orderNum'=>$orderNum];// 打印回调数据到日志Log::info('七牛云回调数据: ' . json_encode($data));// 返回 200 成功响应给七牛云return json(['code'=>200, 'msg'=>'success']);}
}
[2025-07-02T13:38:57+08:00][info] 七牛云回调数据: {"key":"2005\/1751434693.jpg","bucket":"dashisai","classID":"2","smallclassID":"6","userId":"1","orderNum":"202507021320123"}
大功告成!!!