Laravel 七牛雲 sdk 物件儲存 示例 上傳語音

php_yt發表於2020-06-07

引入 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', // 指定檔名
            // )
        }
    }
}

進行上傳

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 協議》,轉載必須註明作者和本文連結

簡潔略帶風騷

相關文章