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 协议》,转载必须注明作者和本文链接
推荐文章: