早睡早起,方能养生
Sleep early rise early, way to keep healthy

ThinkPHP使用七牛云

super
2023-02-24 20:51
views 1113

1)引入

 

composer require qiniu/php-sdk

 

2)use一下

 

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

 

3)代码(ThinkPHP6)

 

/**
 * 文件上传
 */
public function upload()
{
    $file = request()->file('file');
    try {
        validate([
            'file' => 'fileSize:104857600|fileExt:mp3,mp4,rar,zip,gzip,pdf,doc,docx,jpg,jpeg,gif,bmp,png,txt,xls,pptx,xlsx,m4a,mov',
        ])
            ->check(['file' => $file]);
        // 上传到本地服务器
        $save_name = \think\facade\Filesystem::disk('public')->putFile(date('Y') . '/' . date('m') . '/' . date('d'), $file, 'md5');

        $save_path = explode('/', $save_name);

        // 上传到七牛云
        $accessKey = ''; // 你的key
    	$secretKey = ''; // 你的secret
    	$bucket = ''; // 你的bucket名称
    
    	$uploadMgr = new UploadManager();
    	$auth = new Auth($accessKey, $secretKey);

    	$token = $auth->uploadToken($bucket);
    	$res = $uploadMgr->putFile($token, $save_path[count($save_path) - 1], '.' . '/storage/' . $save_name);
    	if (isset($res[0]['key'])) {
    	    unlink('.' . '/storage/' . $save_name); // 删除服务器文件
    	    $qiniu_url = 'https://yoururl.com/'; // 你的七牛cdn链接
    	    success(['path' => $qiniu_url . $res[0]['key']]);
    	} else {
    	    success(['path' => $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/storage/' . $save_name]);
    	}
    } catch (\think\exception\ValidateException $e) {
        error($e->getMessage());
    }
}

 



分享
0 条讨论
top