wqy
2020-03-24 11:33:19
3222

1 获取sdk 

 

https://developer.qiniu.com/kodo/1241/php

 

composer require qiniu/php-sdk

 

2 引入sdk

 

require  '../vendor/qiniu/php-sdk/autoload.php';

 

 

3 代码实现

 

 public function doUpload($userId,$fileName,$fileType = 'image',$dir = 'blog/article'){

        $file =  request()->file($fileName);
        if(!$file){
            error('请选择要上传的文件');
        }
        $fileMd5  = $file->md5();
        $fileSha1 = $file->sha1();

        $findFile = Db::name('asset')->where('file_md5', $fileMd5)->where('file_sha1', $fileSha1)->find();

        if (!empty($findFile)) {
            $data  = [
                'db_src'=>$findFile['file_path'],
                'full_src'=>get_image_preview($findFile['file_path'])
            ];
            return $data;
        }

        // 上传到七牛后保存的文件名
        $saveName = md5($userId.uniqid()).'.png';

        $accessKey = config('upload.qiniu.accessKey');
        $secretKey = config('upload.qiniu.secretKey');
        $bucket = config('upload.qiniu.bucket');

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);


        // 上传到七牛后保存的文件名
        $key = 'upload/'.$dir.'/'.$saveName;
        // 要上传文件的本地路径
        $path = $file->getRealPath();

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $path);

        if ($err !== null) {
            error($err);
        } else {
            $fileKey = $fileMd5 . md5($fileSha1);
            $originalName = $file->getOriginalName();
            $fileSize = $file->getSize();

            Db::name('asset')->insert([
                'user_id'     => $userId,
                'file_key'    => $fileKey,
                'filename'    => $originalName,
                'file_size'   => $fileSize,
                'file_path'   => $key,
                'file_md5'    => $fileMd5,
                'file_sha1'   => $fileSha1,
                'create_time' => time(),
                'suffix'      => 'png'
            ]);

//            @unlink($path);
            $data = [
                'db_src'=>$key,
                'full_src'=>get_image_preview($key)
            ];
            return $data;
        }
    }