<?php
namespace App\Cls;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Qiniu
{
public function __construct()
{
$accessKey = env('QINIU_ACCESS_KEY');
$secretKey = env('QINIU_SECRET_KEY');
$bucket = env('QINIU_BUCKET');
$domain = env('QINIU_URL');
$auth = new Auth($accessKey, $secretKey);
$this->token = $auth->uploadToken($bucket);
$this->uploadMgr = new UploadManager();
}
//base64上传
public function upload_pp($baseImage)
{
if(strpos($baseImage,';base64') === false){
$baseImage = 'data:image/png;base64,'.$baseImage;
}
$match = preg_match('/^(data:\s*image\/(\w+);base64,)/', $baseImage, $result);
if (!$match) {
return ['code'=>0,'msg'=>'不是合规的图片文件'];
}
$baseImage = str_replace($result[1], '', $baseImage);
$baseImage = str_replace(' ', '+', $baseImage);
$type = $result[2];
//新文件名
$key = 'dd/'.date('Ymd') .'/'.guidv4() . '.' . $type;
list($ret, $err) = $this->uploadMgr->put($this->token, $key, base64_decode($baseImage));
if ($err !== null) {
return ['code'=>0,'msg'=>$err];
}
$path = 'https://'.env('QINIU_URL'). '/' .$key;
return ['code'=>1,'data'=>$path];
}
//file对象上传
public function upload_p3($file)
{
$filePath = $file->getClientOriginalName();
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
//新文件名
$key = 'dd/'.date('Ymd') .'/'.guidv4() . '.' . $fileExtension;
list($ret, $err) = $this->uploadMgr->putFile($this->token, $key, $file);
if ($err !== null) {
return ['code'=>0,'msg'=>$err];
}
$path = 'https://'.env('QINIU_URL'). '/' .$key;
return ['code'=>1,'data'=>$path];
}
}
//公共方法
//生成uuid
function guidv4($data = null) {
// Generate 16 bytes (128 bits) of random data or use the data passed into the function.
$data = $data ?? random_bytes(16);
assert(strlen($data) == 16);
// Set version to 0100
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
// Output the 36 character UUID.
//return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
$ga = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
return md5($ga);
}
laravel 七牛云文件上传
最新推荐文章于 2024-04-18 09:37:04 发布