UploadFilesHandler.php 2.5 KB

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