環境: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"}
大功告成!!!