腾讯cos上传

浏览:3528 发布日期:2018/03/20 分类:技术分享 关键字: 腾讯cos上传
use Qcloud\Cos\Client;

/**
 * [local_upload 上传到本地服务器]
 * @author 984270382@qq.com
 * @copyright passboat
 * @return    [type]   [description]
 */
function local_upload($file){
    $path = 'public/uploads/'.date('Ymd/');
    if(!file_exists($path)){
        mkdir ($path,0777,true);
    }
    $name = time().$file['name'];
    $statu = strtolower(substr($name,strrpos($name,'.')+1));
    $allow_type = array('jpg','jpeg','gif','png');
    if(!in_array($statu, $allow_type)){
        return ['code'=>-1,'msg'=>'图片格式错误']; 
    }
    if($file['size']/1024/1024 > 5){
        return ['code'=>-1,'msg'=>'图片大小超过5M!']; 
    }
    if(move_uploaded_file($file['tmp_name'],$path.'/'.$name)){
        return ['path'=>$path,'name'=>$name];        
    }else{
        return false;        
    }
}
/**
 * [tencent_upload cos上传]
 * @author 984270382@qq.com
 * @datetime 2018-03-12T13:22:29+0800
 * @return   [type]                   [description]
 */
function tencent_upload($file)
{
    $tengData = [/*             */];
    $cosClient = new Client(
        [
        'region' => $tengData['region'],
        'credentials'=> [
            'secretId'    => $tengData['secretid'],
            'secretKey' => $tengData['secretkey']]
        ]);
    try {
        // 上传到本地服务器失败
        $res = local_upload($file);
        if($res !== false){
            $path = $res['path'];
            $name = $res['name'];
            $filePath = $path.$name;    
        }else{
             return ['code'=>-1,'上传本地失败']; 
        }

        $result = $cosClient->putObject(
        [
            //bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
            'Bucket' => $tengData['bucket'],
            'Key' => $filePath,
            'Body' => file_get_contents($filePath)
        ]);
        return ['code'=>1,'url'=>$url."/".$filePath ];
    } catch (\Exception $e) {
        return "$e\n";
    }
}
composer require qcloud/cos-sdk-v5 //composer 自己下载
cos文档https://cloud.tencent.com/document/product/436/12266
最近使用到很多接口,本人比较懒,都是用别人的sdk ,希望对你有用,
欢迎关注 欢迎指正!!!
最佳答案
评论( 相关
后面还有条评论,点击查看>>