1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
- namespace App\Handlers;
- use Qiniu\Auth as Auths;
- use Qiniu\Storage\UploadManager;
- use Qiniu\Storage\BucketManager;
- use Illuminate\Support\Facades\Log;
- class UploadFilesHandler
- {
- protected $allowed_ext = array(
- 'video'=>["mp4", "avi", "wmv",'mpeg'],
- 'audio'=>["mp3", "wma", "wav",'flac'],
- 'image'=>["png", "jpg", "gif", 'jpeg']
- );
- /**
- * $file 上传的文件
- * $folder 七牛云文件目录
- * $file_prefix 文件前缀
- * $type 文件类型 video audio image
- */
- public function save($file, $folder, $file_prefix, $type, $max_width = false)
- {
- // 获取七牛云配置信息
- $config = config('filesystems.disks.qiniu');
- Log::info($config);
- // 构建鉴权对象
- $auth = new Auths($config['access_key'], $config['secret_key']);
- // 生成上传 Token
- $token = $auth->uploadToken($config['bucket']);
- //获取文件的绝对路径,但是获取到的在本地不能打开
- $filePath = $file->getRealPath();
- //获取文件的扩展名
- $extension = $file->getClientOriginalExtension();
- //获取上传文件的名称
- // $ext_name = $file->getClientOriginalName();
- Log::info($this->allowed_ext[$type]);
- //判断文件格式是否正确
- if (empty($extension) || !in_array(strtolower($extension), $this->allowed_ext[$type])) {
- return false;
- }
- // 拼接文件名,加前缀是为了增加辨析度,前缀可以是相关数据模型的 ID
- // 值如:1_1493521050_7BVc9v9ujP.png
- if($file_prefix){
- $filename = $file_prefix . '_' . time() . '_' . str_random(10) . '.' . $extension;
- }else{
- $filename = time() . '_' . str_random(10) . '.' . $extension;
- }
- // 初始化 UploadManager 对象并进行文件的上传。
- $uploadMgr = new UploadManager();
- // 调用 UploadManager 的 putFile 方法进行文件的上传。
- $pathname= $config['dirname'].'/'.$folder.'/'.$filename;
- Log::info([$token, $pathname, $filePath]);
- try{
- $uploadMgr->putFile($token, $pathname, $filePath);
- }catch(\Exception $e){
- Log::info($e->getMessage());
- return false;
- }
- // 返回文件完整路径
- Log::info($config['domain'].'/'.$pathname);
- return [
- 'path' => $config['domain'].'/'.$pathname
- ];
- }
- }
|