限时免费试用:欢迎注册 api.bigmodel.org ,快速体验大模型 API 接入服务。
当前位置:首页 >开发者 >PHP笔记 >PHP高级

实例 | tp5使用七牛云上传图片和文件/删除文件

分类:PHP高级时间:2018-10-31浏览:5655
thinkphp5中使用七牛云 下载 https://github.com/qiniu/php-sdk vendor文件下
新建文件 application/extra/qiniu.php
return [
'ACCESSKEY' => 'PkQcItX7rJL7',//你的accessKey
'SECRETKEY' => 'eaWM7C_COYLjX8VKVGinzv1',//你的secretKey
'BUCKET' => 'zin',//上传的空间
'DOMAIN'=>'pdn.com'//空间绑定的域名
];
html



  


  

php
isPost()){
            $file = request()->file('image');
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀

            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            require_once APP_PATH . '/../vendor/qiniu/autoload.php';
            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = config("qiniu.ACCESSKEY");
            $secretKey = config("qiniu.SECRETKEY");
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket = config("qiniu.BUCKET");
            $domain = config("qiniu.DOMAINImage");
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return json(["err"=>1,"msg"=>$err,"data"=>""]);die;
            } else {
                //返回图片的完整URL
                return  json(["err"=>0,"msg"=>"上传完成","data"=>uploadreg($domain . $ret['key'])]);die;
            }
        }
        return view(); 
    }

    //  删除
    public function delete($name)
    {
        $delFileName = input("name");
        if( $delFileName ==null){
            echo "参数不正确";die;
        }
        require_once APP_PATH . '/../vendor/qiniu/autoload.php';
        // 构建鉴权对象
        $auth = new Auth(config("qiniu.ACCESSKEY"),config("qiniu.SECRETKEY"));

        // 配置
        $config = new \Qiniu\Config();

        // 管理资源
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);

        // 删除文件操作
        $res = $bucketManager->delete(config("qiniu.BUCKET"), $delFileName);

        if (is_null($res)) {
            // 为null成功
            // return true;
            echo "成功";
        }else{
            echo "失败";
        }
    }
    
    
}

?>
本站文章如未注明出处均为原创,转载请注明出处,如有侵权请邮件联系站长。
0/500
Share your thoughts respectfully.