LocalAdapter.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * @desc 本地适配器
  4. *
  5. * @author Tinywan(ShaoBo Wan)
  6. * @date 2022/3/7 19:54
  7. */
  8. declare(strict_types=1);
  9. namespace app\common\storage;
  10. use Intervention\Image\ImageManagerStatic as Image;
  11. use Tinywan\Storage\Adapter\AdapterAbstract;
  12. use Tinywan\Storage\Exception\StorageException;
  13. class LocalAdapter extends AdapterAbstract
  14. {
  15. /**
  16. * @desc: 方法描述
  17. *
  18. * @author Tinywan(ShaoBo Wan)
  19. */
  20. public function uploadFile(array $options = []): array
  21. {
  22. $result = [];
  23. $basePath = $this->config['root'] . $this->config['dirname'] . DIRECTORY_SEPARATOR;
  24. if (!$this->createDir($basePath)) {
  25. throw new StorageException('文件夹创建失败,请核查是否有对应权限。');
  26. }
  27. if (!$this->createDir($basePath . '/thumb')) {
  28. throw new StorageException('文件夹创建失败,请核查是否有对应权限。');
  29. }
  30. $baseUrl = $this->config['domain'] . $this->config['uri'] . str_replace(DIRECTORY_SEPARATOR, '/', $this->config['dirname']) . DIRECTORY_SEPARATOR;
  31. foreach ($this->files as $key => $file) {
  32. // 缩略
  33. $image = Image::make($file);
  34. $uniqueId = hash_file($this->algo, $file->getPathname());
  35. $saveFilename = $uniqueId . '.' . $file->getUploadExtension();
  36. $originSavePath = $basePath . $saveFilename;
  37. $thumbSavePath = $basePath . 'thumb' . DIRECTORY_SEPARATOR . $saveFilename;
  38. $temp = [
  39. 'key' => $key,
  40. 'origin_name' => $file->getUploadName(),
  41. 'save_name' => $saveFilename,
  42. 'save_path' => $thumbSavePath,
  43. 'url' => $baseUrl . 'thumb' . DIRECTORY_SEPARATOR . $saveFilename,
  44. 'unique_id' => $uniqueId,
  45. 'size' => $file->getSize(),
  46. 'mime_type' => $file->getUploadMineType(),
  47. 'extension' => $file->getUploadExtension(),
  48. ];
  49. // 保存原图
  50. $file->move($originSavePath);
  51. // 保存缩略图
  52. $imgWidth = $image->width();
  53. $imgHeight = $image->height();
  54. $rate = round($imgWidth / 200, 2);
  55. $height = intval($imgHeight / $rate);
  56. $image = $image->resize(200, $height);
  57. $encoded = $image->encode('jpg');
  58. $encoded->save($thumbSavePath);
  59. // $file->move($savePath);
  60. array_push($result, $temp);
  61. }
  62. return $result;
  63. }
  64. /**
  65. * @desc: createDir 描述
  66. */
  67. protected function createDir(string $path): bool
  68. {
  69. if (is_dir($path)) {
  70. return true;
  71. }
  72. $parent = dirname($path);
  73. if (!is_dir($parent)) {
  74. if (!$this->createDir($parent)) {
  75. return false;
  76. }
  77. }
  78. return mkdir($path);
  79. }
  80. }