UploadFilesHandler.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Handlers;
  3. use Qiniu\Auth as Auths;
  4. use Qiniu\Storage\UploadManager;
  5. use Qiniu\Storage\BucketManager;
  6. use Illuminate\Support\Facades\Log;
  7. class UploadFilesHandler
  8. {
  9. protected $allowed_ext = array(
  10. 'video'=>["mp4", "avi", "wmv",'mpeg'],
  11. 'audio'=>["mp3", "wma", "wav",'flac'],
  12. 'image'=>["png", "jpg", "gif", 'jpeg']
  13. );
  14. /**
  15. * $file 上传的文件
  16. * $folder 七牛云文件目录
  17. * $file_prefix 文件前缀
  18. * $type 文件类型 video audio image
  19. */
  20. public function save($file, $folder, $file_prefix, $type, $max_width = false)
  21. {
  22. // 获取七牛云配置信息
  23. $config = config('filesystems.disks.qiniu');
  24. Log::info($config);
  25. // 构建鉴权对象
  26. $auth = new Auths($config['access_key'], $config['secret_key']);
  27. // 生成上传 Token
  28. $token = $auth->uploadToken($config['bucket']);
  29. //获取文件的绝对路径,但是获取到的在本地不能打开
  30. $filePath = $file->getRealPath();
  31. //获取文件的扩展名
  32. $extension = $file->getClientOriginalExtension();
  33. //获取上传文件的名称
  34. // $ext_name = $file->getClientOriginalName();
  35. Log::info($this->allowed_ext[$type]);
  36. //判断文件格式是否正确
  37. if (empty($extension) || !in_array(strtolower($extension), $this->allowed_ext[$type])) {
  38. return false;
  39. }
  40. // 拼接文件名,加前缀是为了增加辨析度,前缀可以是相关数据模型的 ID
  41. // 值如:1_1493521050_7BVc9v9ujP.png
  42. if($file_prefix){
  43. $filename = $file_prefix . '_' . time() . '_' . str_random(10) . '.' . $extension;
  44. }else{
  45. $filename = time() . '_' . str_random(10) . '.' . $extension;
  46. }
  47. // 初始化 UploadManager 对象并进行文件的上传。
  48. $uploadMgr = new UploadManager();
  49. // 调用 UploadManager 的 putFile 方法进行文件的上传。
  50. $pathname= $config['dirname'].'/'.$folder.'/'.$filename;
  51. Log::info([$token, $pathname, $filePath]);
  52. try{
  53. $uploadMgr->putFile($token, $pathname, $filePath);
  54. }catch(\Exception $e){
  55. Log::info($e->getMessage());
  56. return false;
  57. }
  58. // 返回文件完整路径
  59. Log::info($config['domain'].'/'.$pathname);
  60. return [
  61. 'path' => $config['domain'].'/'.$pathname
  62. ];
  63. }
  64. }