FileUploadService.php 1.1 KB

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