AttachmentHelper.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. <?php
  2. namespace App\Helper;
  3. use FFMpeg;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\UploadedFile;
  6. use OSS\OssClient;
  7. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  8. use App\Models\BaseAttachment;
  9. trait AttachmentHelper
  10. {
  11. public function __construct()
  12. {
  13. // 在 .env 文件里配置下面可测试文件上传OSS
  14. // ALI_OSS_ACCESS_ID=LTAI5tHMYxyoEkmGqQZjbpmk
  15. // ALI_OSS_ACCESS_KEY=Fqj8J1JH0yyRpLvOjNFj5usjvfvHns
  16. // ALI_OSS_BUCKET=zhengda
  17. // ALI_OSS_ENDPOINT=oss-cn-chengdu.aliyuncs.com
  18. $this->fileDriver = env('FILESYSTEM_DRIVER');
  19. $this->bucket = env('ALI_OSS_BUCKET');
  20. $this->accessId = env('ALI_OSS_ACCESS_ID');
  21. $this->accessKey = env('ALI_OSS_ACCESS_KEY');
  22. $this->endPoint = env('ALI_OSS_ENDPOINT');
  23. $this->ossClient = new OssClient($this->accessId, $this->accessKey, $this->endPoint);
  24. }
  25. /**
  26. * @param string $tag
  27. * @param float|int $size
  28. *
  29. * @return array|mixed
  30. *
  31. * @throws \Exception
  32. */
  33. public function uploadAttachment(Request $request, $key, $tag = 'files', $size = 200 * 1024 * 1024, array $mimeType = [])
  34. {
  35. if ($request->hasFile($key)) {
  36. $files = $request->file($key);
  37. if (null === $files) {
  38. throw new \Exception(trans('api.ATTACHMENT_FILE_NULL'));
  39. }
  40. if ($files instanceof UploadedFile) {
  41. $files = [$files];
  42. }
  43. $result = [];
  44. foreach ($files as $idx => $file) {
  45. if (!$file->isValid()) {
  46. throw new \Exception(trans('api.ATTACHMENT_TYPE_ERROR'));
  47. continue;
  48. }
  49. $fileSize = $file->getSize();
  50. if ($fileSize > $size) {
  51. throw new \Exception(trans('api.ATTACHMENT_SIZE_EXCEEDED'));
  52. continue;
  53. }
  54. $fileMimeType = $file->getMimeType();
  55. if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
  56. throw new \Exception(trans('api.ATTACHMENT_TYPE_ERROR'));
  57. continue;
  58. }
  59. $clientName = $file->getClientOriginalName();
  60. $md5 = md5($clientName . time());
  61. $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
  62. try {
  63. // 本地上传
  64. if ('local' == env('FILESYSTEM_DRIVER')) {
  65. $rel_path = '/upload/' . $tag . '/' . date('Ymd');
  66. $path = public_path() . $rel_path;
  67. if (!file_exists($path)) {
  68. if (!@mkdir($path, 0755, true)) {
  69. throw new \Exception(trans('api.ATTACHMENT_MAKE_FOLDER_ERROR'));
  70. }
  71. }
  72. $file->move($path, $md5_filename);
  73. $realPath = $path . '/' . $md5_filename;
  74. $urlPath = $rel_path . '/' . $md5_filename;
  75. if ('video/mp4' == $fileMimeType || 'video/quicktime' == $fileMimeType) {
  76. $ffmpeg = FFMpeg\FFMpeg::create([
  77. 'ffmpeg.binaries' => '/usr/bin/ffmpeg',
  78. 'ffprobe.binaries' => '/usr/bin/ffprobe',
  79. ]);
  80. $video = $ffmpeg->open($realPath);
  81. $vpath = public_path() . '/upload/vpic/';
  82. if (!file_exists($vpath)) {
  83. if (!@mkdir($vpath, 0755, true)) {
  84. return trans('api.ATTACHMENT_MAKE_FOLDER_ERROR');
  85. }
  86. }
  87. $pic = $vpath . $md5 . '.jpg';
  88. $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(1))->save($pic);
  89. }
  90. $result[$idx] = 'http://' . $_SERVER['HTTP_HOST'] . $urlPath;
  91. } elseif ('oss' == env('FILESYSTEM_DRIVER')) {
  92. $tmppath = $file->getRealPath(); // 获取上传图片的临时地址
  93. $fileName = date('YmdHis') . rand(10000, 99999) . '.' . $file->getClientOriginalExtension(); // 生成文件名
  94. $pathName = $tag . '/' . date('Y-m') . '/' . $fileName;
  95. $upResult = $this->ossClient->uploadFile($this->bucket, $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]); // 上传图片到阿里云OSS
  96. $url = $upResult['info']['url'];
  97. $realPath = $url;
  98. $urlPath = $url;
  99. $result[$idx] = $url;
  100. }
  101. // 将上传的图片存入到数据表作为记录
  102. $attachment = new BaseAttachment();
  103. $attachment->name = $clientName;
  104. $attachment->md5 = $md5;
  105. $attachment->path = $realPath;
  106. $attachment->url = $urlPath;
  107. $attachment->size = $fileSize;
  108. $attachment->file_type = $fileMimeType;
  109. if (!$attachment->save()) {
  110. @unlink($realPath);
  111. throw new \Exception(trans('api.ATTACHMENT_SAVE_ERROR'));
  112. }
  113. } catch (FileException $e) {
  114. throw new \Exception(trans('api.ATTACHMENT_UPLOAD_INVALID'));
  115. }
  116. }
  117. if (1 == count($result)) {
  118. return array_shift($result);
  119. }
  120. return $result;
  121. }
  122. throw new \Exception(trans('api.ATTACHMENT_UPLOAD_INVALID'));
  123. }
  124. /**
  125. * 删除附件.
  126. *
  127. * @param $picUrl 图片地址
  128. *
  129. * @return int 错误码or 0(成功)
  130. */
  131. public function deleteAttachment($picUrl)
  132. {
  133. if ('local' == $this->fileDriver) {
  134. $attachment = BaseAttachment::where(['path' => $picUrl])->first();
  135. if (!$attachment) {
  136. return false;
  137. }
  138. if (file_exists($attachment->path)) {
  139. if (@unlink($attachment->path)) {
  140. if (!$attachment->delete()) {
  141. return false;
  142. }
  143. } else {
  144. return false;
  145. }
  146. } else {
  147. return false;
  148. }
  149. } elseif ('oss' == $this->fileDriver) {
  150. $this->ossClient->deleteObject($this->bucket, $picUrl);
  151. }
  152. return true;
  153. }
  154. }