最近接了个需求,把ueditor百度编辑器的上传图片,修改到上传至腾讯云的对象存储器
首先需要腾讯云的 SecretId SecretKey bucket (存储桶) region(bucket所在地区)
sdk
https://github.com/tencentyun/cos-php-sdk-v5/releases
文档
https://cloud.tencent.com/document/product/436/12266
第一步 composer install 导入 sdk
tp后台中,使用包管理工具composer 导入sdk
第二步,编写接口
/** * 上传图片至腾讯云cos接口 */ public function imagesToCosPub() { $file_input_name = "file"; $file = $this->request->file($file_input_name); $tencentyun_config = config('tencentyun'); if ($file) { $secretId = $tencentyun_config['secretId']; //"云 API ** SecretId"; $secretKey = $tencentyun_config['secretKey']; //"云 API ** SecretKey"; $region = $tencentyun_config['region']; //设置一个默认的存储桶地域 $cosClient = new QcloudCosClient( array( 'region' => $region, 'schema' => 'http', //协议头部,默认为http 'credentials' => array( 'secretId' => $secretId, 'secretKey' => $secretKey ) ) ); $bucket = $tencentyun_config['bucket']; //存储桶名称 格式:BucketName-APPID $file_Info = $file->getInfo(); $filepath = $file_Info["tmp_name"]; $files = fopen($filepath, "rb"); //设置一个对象键(尽量不包含特殊符号) $keyv = rand(0, 99999999); $fileKey = date('Y') . '/' . date('m') . '/' . date('d') . '/' . $keyv . '.' . explode("/", $file_Info["type"])[1]; //此处的 key 为对象键,对象键是对象在存储桶中的唯一标识 # 上传文件 try { if ($files) { $result = $cosClient->upload( $bucket = $bucket, $key = $fileKey, $body = $files ); # 请求成功 $path = '/' . $fileKey; $data = []; $data['state'] = 'SUCCESS'; $data['title'] = $file_Info["name"]; $data['alt'] = $file_Info["name"]; $data['url'] = $path; return json($data); } } catch (Exception $e) { // 请求失败 echo ($e); } } else { $imagecofig = []; $imagecofig['imageActionName'] = "uploadimage"; $imagecofig['imageUrlPrefix'] = "https://xxx.cos.ap-guangzhou.myqcloud.com"; $imagecofig['imageFieldName'] = "file"; $imagecofig['catcherAllowFiles'] = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; $imagecofig['imageAllowFiles'] = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; return json($imagecofig); } }
第三步,在使用ueditor的地方,加上代码,重新配置serverUrl, 替换成你所写的接口
jQuery(document).ready(function () { ueditor = UE.getEditor($('.js-ueditor').attr('name'), { initialFrameHeight: 400, //初始化编辑器高度,默认320 initialFrameWidth: '100%', autoHeightEnabled: false, //是否自动长高 maximumWords: 50000, //允许的最大字符数 serverUrl:"/admin.php/cms/content/imagesToCosPub", }); });
其中遇到难点,不知道$body 的files 应该放什么内容,后来研究发现,是file的“tmp_name”。 request ->file('file') 得出来的数据 需要用$file->getInfo()方法才能提取出文件的信息。
$Key 差不多可以理解成路径。不同等级 ‘/’ 划分文件层级,最后再拼接文件名称 和文件后缀。