Laravel 七牛云 sdk 对象存储 示例 上传语音

引入 sdk

"qiniu/php-sdk": "^7.2"

使用 sdk

<?php
namespace App\Service;

use Qiniu\Auth;
use Illuminate\Support\Facades\Log;

class Qiniu
{
    public static function uploadVoice($bucket, $fileName, $realPath)
    {
        if( !in_array($bucket, ['voice'])){
            return false;
        }
        $config = config('filesystems.disks.qiniu');

        $auth = new Auth($config['access_key'], $config['secret_key']);

        $upManager = new \Qiniu\Storage\UploadManager();

        // 压缩
        $savekey = \Qiniu\base64_urlSafeEncode($bucket.':'.$fileName);
        $fops = $config['fops'].'|saveas/'.$savekey;
        // 传入该参数 对上传文件立即进行处理(压缩)
        $policy = [
            'persistentOps' => $fops,
            'persistentPipeline' => $config['pipeline'], //队列
            // 'persistentNotifyUrl' => $config['notify_url'], //该项为转码处理结果回调
        ];

        $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);

        list($ret, $err) = $upManager->putFile($uptoken, $fileName, $realPath);

        if( $err !== null ){
            Log::error($err);
            return false;
        }else{
            Log::info($ret);
            return $config['bucket'][$bucket]['domain'].$ret['key'];
            // array (
            //   'hash' => 'FiFxLpGZ-avREF3m20ZBOwOydafz', // 不指定文件名的情况下
            //   'key' => '20200604020041/5ed88e098fa91.mp3', // 指定文件名
            // )
        }
    }
}

附 filesystem config

'qiniu' => [
    'access_key' => '',
    'secret_key' => '',
    // 'upload_url' => 'http://xx.qiniup.com',
    'fops'  => 'avthumb/mp3/..',  //带数据处理的凭证
    'pipeline' => 'voice', // 队列
    'notify_url' => '',
    'bucket'     => [
        'voice' => [
            'domain'    => 'http://voice.xx.xx.com/'
        ],
    ]
]

进行上传

if( $request->hasFile('voice') )
{
    $file = $request->file('voice');
    $size = $request->input('size');//时长 由前端传入
    if( $file->isValid() ){
        $realPath = $file->getRealPath(); // 文件的绝对路径
        $fileName =date('Ymdhis').'/'.uniqid().'.mp3';
        $url = Qiniu::uploadVoice('voice',$fileName,$realPath);
        if( $url === false ){
            return Y::error('语音上传失败');
        }
    }else{
        return Y::error('语音上传失败');
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
welcome come back
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
98
粉丝
25
喜欢
160
收藏
360
排名:315
访问:3.0 万
私信
所有博文
社区赞助商