You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.4 KiB

  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Constants\v3\ErrorCode;
  4. use App\Service\v3\Interfaces\AttachmentServiceInterface;
  5. use League\Flysystem\FilesystemNotFoundException;
  6. class AttachmentService implements AttachmentServiceInterface
  7. {
  8. /**
  9. * @inheritDoc
  10. */
  11. public function formUpload($file, $path, $filesystem, $attachmenttype = 'image')
  12. {
  13. $fileRealPath = $file->getRealPath();
  14. $fileHash = md5_file($fileRealPath);
  15. $path = $this->getBasePath($path, $attachmenttype);
  16. $fileName = $path . '/' . $fileHash . '.' . $file->getExtension();
  17. $stream = fopen($fileRealPath, 'r+');
  18. $filesystem->writeStream($fileName, $stream);
  19. fclose($stream);
  20. return $fileName;
  21. }
  22. /**
  23. * @inheritDoc
  24. */
  25. public function base64Upload($contents, $path, $filesystem)
  26. {
  27. preg_match('/^(data:\s*image\/(\w+);base64,)/', $contents, $result);
  28. if (empty($result)) {
  29. throw new FilesystemNotFoundException(ErrorCode::getMessage(ErrorCode::UPLOAD_INVALID),ErrorCode::UPLOAD_INVALID);
  30. }
  31. $contents = base64_decode(str_replace($result[1], '', $contents));
  32. $fileHash = md5($contents);
  33. $path = $this->getBasePath($path);
  34. $fileName = $path . '/' . $fileHash . '.' . $result[2];
  35. $filesystem->write($fileName, $contents);
  36. return $fileName;
  37. }
  38. protected function getBasePath($path, $attachmenttype = 'image')
  39. {
  40. switch ($attachmenttype) {
  41. case 'image':
  42. $baseDir = env('IMAGE_BASE', '/attachment/images');
  43. break;
  44. case 'file':
  45. $baseDir = env('FILES_BASE', '/attachment/files');
  46. break;
  47. default:
  48. $baseDir = env('FILES_BASE', '/attachment');
  49. break;
  50. }
  51. $path = $path ? '/'.$path : '';
  52. $path .= '/'.date('Y').'/'.date('m').'/'.date('d');
  53. return $baseDir.$path;
  54. }
  55. public function switchImgToAliOss($path, $bucket = '')
  56. {
  57. if (strpos($path, 'http') === false || strpos($path, 'https') === false) {
  58. $path = config('alioss.img_host') . '/' . $path;
  59. } else {
  60. $temp = explode('//', $path);
  61. $temp = explode('/', $temp[1]);
  62. unset($temp[0]);
  63. $path = config('alioss.img_host') . '/' . implode('/', $temp);
  64. }
  65. return $path . $bucket;
  66. }
  67. }