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
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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