FileUploadService.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\Storage;
  4. class FileUploadService extends Service
  5. {
  6. //文件类型
  7. const FILE_TYPE = [
  8. 'txt',
  9. 'jpg',
  10. 'png',
  11. 'gif',
  12. 'jpeg',
  13. 'zip',
  14. 'rar'
  15. ];
  16. public function uploadFile($file){
  17. $file_name = [];
  18. if(is_array($file)){
  19. foreach ($file as $value){
  20. $file_name[] = $this->saveFile($value);
  21. }
  22. }else{
  23. $file_name[] = $this->saveFile($file);
  24. }
  25. return [true, $file_name];
  26. }
  27. public function saveFile($file){
  28. // 获取文件相关信息
  29. $ext = $file->getClientOriginalExtension(); // 扩展名
  30. $realPath = $file->getRealPath(); //临时文件的绝对路径
  31. $ext = strtolower($ext);
  32. if (! in_array($ext, self::FILE_TYPE)){
  33. $str = '文件格式为:';
  34. foreach (self::FILE_TYPE as $value){
  35. $str.= $value . ' ' ;
  36. }
  37. return [false,$str];
  38. }
  39. // 上传文件
  40. $file_name = date("Ymd").time().rand(1000,9999);
  41. $filename = $file_name.'.' . $ext;
  42. // 使用我们新建的uploads本地存储空间(目录)
  43. Storage::disk('public')->put('upload_files/'.$filename, file_get_contents($realPath));
  44. return '/api/uploadFiles/'.$file_name;
  45. }
  46. }