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.

72 lines
1.9 KiB

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