FileUploadService.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. 'xlsx',
  16. 'xls'
  17. ];
  18. public function uploadFile($file){
  19. // 获取文件相关信息
  20. $ext = $file->getClientOriginalExtension(); // 扩展名
  21. $realPath = $file->getRealPath(); //临时文件的绝对路径
  22. $ext = strtolower($ext);
  23. if (! in_array($ext, self::FILE_TYPE)){
  24. $str = '文件格式为:';
  25. foreach (self::FILE_TYPE as $value){
  26. $str.= $value . ' ' ;
  27. }
  28. return [false,$str];
  29. }
  30. // 上传文件
  31. $file_name = date("Ymd").time().rand(1000,9999);
  32. $filename = $file_name.'.' . $ext;
  33. // 使用我们新建的uploads本地存储空间(目录)
  34. Storage::disk('public')->put('upload_files/'.$filename, file_get_contents($realPath));
  35. return [true,'/api/uploadFiles/'.$file_name];
  36. }
  37. }