1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| <?php
use OSS\OssClient; use RingCentral\Psr7\Response;
$bucket = getenv('oss_bucket');
$region = getenv('oss_region');
$oss = null;
function initializer($context) { global $oss, $region;
if(is_null($oss)) { $oss = new OssClient( $context['credentials']['accessKeyId'], $context['credentials']['accessKeySecret'], 'https://oss-' . $region . '.aliyuncs.com', false, $context['credentials']['securityToken'] ); } }
function handler($request, $context): Response{ global $oss, $bucket;
if($request->getMethod() === 'GET') { return new Response( 200, [ 'Content-type' => 'text/html; charset=utf-8', ], file_get_contents(__DIR__ . '/index.html') ); }
$types = [ 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', ];
$param = $request->getQueryParams();
if(!isset($param['type'])) { return error('参数错误'); }
$type = $param['type'];
if(!isset($types[$type])) { return error('不支持此格式'); }
$filepath = generate_path($types[$type]);
$sign = $oss->signUrl($bucket, $filepath, 10 * 60, 'PUT');
return result([ 'sign' => $sign, 'url' => 'https://' . getenv('cdn_domain') . '/' . $filepath, ]); }
function generate_path($suffix) { global $oss, $bucket;
$path = date('Ymd/') . str_rand() . '.' . $suffix;
$exist = $oss->doesObjectExist($bucket, $path);
if($exist) { return generate_path($suffix); }
return $path; }
function str_rand(int $length = 6){ $length = ($length < 4) ? 4 : $length; return bin2hex(random_bytes(($length-($length%2))/2)); }
function result($data = []): Response { return new Response( 200, [], json_encode([ 'code' => 1, 'data' => $data, ]) ); }
function error($msg): Response { return new Response( 200, [], json_encode([ 'code' => 0, 'msg' => $msg, ]) ); }
|