The content of this article is about Thinkphp5 docking with Baidu Cloud Object Storage BOS (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First download the SDK package, you can download it from the official website, or use composer in the project root directory.
composer require baidubce/bce-sdk-php
There are five files in the compressed package, but only two are actually used, and then placed in the extend file directory
Introduce it into the controller you need to use
//如果是用composer 引入的直接use就可以了 : use BaiduBce\Services\Bos\BosClient; //如果使用的压缩包: include_once './extend/BaiduBce.phar';//下面是文件结构 require './extend/SampleConf.php';// 配置信息 BaiduBce.phar ├──src │ └── BaiduBce //composer直接下载的就是这个文件 │ ├── Auth //BCE签名相关 │ ├── Exception //BCE客户端的异常 │ ├── Http //BCE的Http通信相关 │ ├── Log //BCE日志 │ ├── Services │ │ └── Bos //BOS主目录,此目录必须保留 │ │ ├── BosClient.php //BOS操作类,所有操作可以通过BosClient类可以完成 │ │ ├── BosOptions.php //BOS自定义配置 │ │ └── CannedAcl.php //CannedAcl模块 │ └── Util //BCE公用工具 └──vendor //第三方库
Upload method:
public function test_upload() { error_reporting(-1); $file = request()->file('file'); if ($file) { $info = $file->move(ROOT_PATH . 'uploads'); if ($info) { $BOS_TEST_CONFIG = array( 'credentials' => array( 'accessKeyId' => 'your accessKeyId', 'secretAccessKey' => 'your aecretAccessKey', ), 'endpoint' => 'bucket域名', ); $client = new BosClient($BOS_TEST_CONFIG);//如果是有配置文件直接在配置文件里面配置信息就可以了不需要写上面的数组。 $bucketName = 'rests';//bucket名字,相当于你在bucket创建好的那个文件夹,如果没有会自动创建。 $client->putObjectFromFile($bucketName, $info->getSaveName(), 'uploads' . DS . $info->getSaveName()); //第一个参数:bucket名字、第二个参数:文件名字、第三个参数:文件路径。 // 成功上传后 获取上传信息 $data['code'] = 0; $data['msg'] = ''; $data['list'] = [ 'src' => 'cartoon/' . $info->getSaveName(), 'name' => $info->getFilename(), 'preview' => 'uploads' . DS . $info->getSaveName(), ]; //上面的返回数据是看个人项目需要的数据 $url = ROOT_PATH . 'uploads' . DS . $info->getSaveName(); unset($info);//如果不释放这个变量下面的unlink()函数会报错。 if (file_exists($url)) { unlink($url);//删除本地文件 } echo json_encode($data); } else { // 上传失败获取错误信息 echo $file->getError(); } } }
Delete method :
/** * 删除百度云存储文件 * @access public * @param string $object 文件名字 * @param string $bucket BucketName * @return false|File */ public function file_del($object, $bucket = 'test') { $BOS_TEST_CONFIG = array( 'credentials' => array( 'accessKeyId' => 'your accessKeyId', 'secretAccessKey' => 'your secretAccessKey', ), 'endpoint' => 'bucket域名', ); $client = new BosClient($BOS_TEST_CONFIG); $client->deleteObject($bucket, $object); }
The above is the detailed content of Thinkphp5 connects to Baidu Cloud Object Storage BOS (code example). For more information, please follow other related articles on the PHP Chinese website!