Upload.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <?php
  2. namespace app\common\library;
  3. use Throwable;
  4. use ba\Random;
  5. use think\File;
  6. use ba\Filesystem;
  7. use think\Exception;
  8. use think\facade\Config;
  9. use think\file\UploadedFile;
  10. use app\common\model\Attachment;
  11. /**
  12. * 上传
  13. */
  14. class Upload
  15. {
  16. /**
  17. * 配置信息
  18. * @var array
  19. */
  20. protected array $config = [];
  21. /**
  22. * @var ?UploadedFile
  23. */
  24. protected ?UploadedFile $file = null;
  25. /**
  26. * 是否是图片
  27. * @var bool
  28. */
  29. protected bool $isImage = false;
  30. /**
  31. * 文件信息
  32. * @var array
  33. */
  34. protected array $fileInfo;
  35. /**
  36. * 细目(存储目录)
  37. * @var string
  38. */
  39. protected string $topic = 'default';
  40. /**
  41. * 构造方法
  42. * @param ?UploadedFile $file 上传的文件
  43. * @param array $config 配置
  44. * @throws Throwable
  45. */
  46. public function __construct(?UploadedFile $file = null, array $config = [])
  47. {
  48. $this->config = Config::get('upload');
  49. if ($config) {
  50. $this->config = array_merge($this->config, $config);
  51. }
  52. if ($file) {
  53. $this->setFile($file);
  54. }
  55. }
  56. /**
  57. * 设置文件
  58. * @param UploadedFile $file
  59. * @return array 文件信息
  60. * @throws Throwable
  61. */
  62. public function setFile(UploadedFile $file): array
  63. {
  64. if (empty($file)) {
  65. throw new Exception(__('No files were uploaded'), 10001);
  66. }
  67. $suffix = strtolower($file->extension());
  68. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  69. $fileInfo['suffix'] = $suffix;
  70. $fileInfo['type'] = $file->getOriginalMime();
  71. $fileInfo['size'] = $file->getSize();
  72. $fileInfo['name'] = $file->getOriginalName();
  73. $fileInfo['sha1'] = $file->sha1();
  74. $this->file = $file;
  75. $this->fileInfo = $fileInfo;
  76. return $fileInfo;
  77. }
  78. /**
  79. * 设置细目(存储目录)
  80. */
  81. public function setTopic(string $topic): Upload
  82. {
  83. $this->topic = $topic;
  84. return $this;
  85. }
  86. /**
  87. * 检查文件类型是否允许上传
  88. * @return bool
  89. * @throws Throwable
  90. */
  91. protected function checkMimetype(): bool
  92. {
  93. $mimetypeArr = explode(',', strtolower($this->config['mimetype']));
  94. $typeArr = explode('/', $this->fileInfo['type']);
  95. // 验证文件后缀
  96. if ($this->config['mimetype'] === '*'
  97. || in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
  98. || in_array($this->fileInfo['type'], $mimetypeArr) || in_array($typeArr[0] . "/*", $mimetypeArr)) {
  99. return true;
  100. }
  101. throw new Exception(__('The uploaded file format is not allowed'), 10002);
  102. }
  103. /**
  104. * 是否是图片并设置好相关属性
  105. * @return bool
  106. * @throws Throwable
  107. */
  108. protected function checkIsImage(): bool
  109. {
  110. if (in_array($this->fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($this->fileInfo['suffix'], ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
  111. $imgInfo = getimagesize($this->file->getPathname());
  112. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  113. throw new Exception(__('The uploaded image file is not a valid image'));
  114. }
  115. $this->fileInfo['width'] = $imgInfo[0];
  116. $this->fileInfo['height'] = $imgInfo[1];
  117. $this->isImage = true;
  118. return true;
  119. }
  120. return false;
  121. }
  122. /**
  123. * 上传的文件是否为图片
  124. * @return bool
  125. */
  126. public function isImage(): bool
  127. {
  128. return $this->isImage;
  129. }
  130. /**
  131. * 检查文件大小是否允许上传
  132. * @throws Throwable
  133. */
  134. protected function checkSize(): void
  135. {
  136. $size = Filesystem::fileUnitToByte($this->config['maxsize']);
  137. if ($this->fileInfo['size'] > $size) {
  138. throw new Exception(__('The uploaded file is too large (%sMiB), Maximum file size:%sMiB', [
  139. round($this->fileInfo['size'] / pow(1024, 2), 2),
  140. round($size / pow(1024, 2), 2)
  141. ]));
  142. }
  143. }
  144. /**
  145. * 获取文件后缀
  146. * @return string
  147. */
  148. public function getSuffix(): string
  149. {
  150. return $this->fileInfo['suffix'] ?: 'file';
  151. }
  152. /**
  153. * 获取文件保存名
  154. * @param ?string $saveName
  155. * @param ?string $filename
  156. * @param ?string $sha1
  157. * @return string
  158. */
  159. public function getSaveName(?string $saveName = null, ?string $filename = null, ?string $sha1 = null): string
  160. {
  161. if ($filename) {
  162. $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  163. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  164. } else {
  165. $suffix = $this->fileInfo['suffix'];
  166. }
  167. $filename = $filename ?: ($suffix ? substr($this->fileInfo['name'], 0, strripos($this->fileInfo['name'], '.')) : $this->fileInfo['name']);
  168. $sha1 = $sha1 ?: $this->fileInfo['sha1'];
  169. $replaceArr = [
  170. '{topic}' => $this->topic,
  171. '{year}' => date("Y"),
  172. '{mon}' => date("m"),
  173. '{day}' => date("d"),
  174. '{hour}' => date("H"),
  175. '{min}' => date("i"),
  176. '{sec}' => date("s"),
  177. '{random}' => Random::build(),
  178. '{random32}' => Random::build('alnum', 32),
  179. '{filename}' => mb_substr($filename, 0, 15),
  180. '{suffix}' => $suffix,
  181. '{.suffix}' => $suffix ? '.' . $suffix : '',
  182. '{filesha1}' => $sha1,
  183. ];
  184. $saveName = $saveName ?: $this->config['savename'];
  185. return str_replace(array_keys($replaceArr), array_values($replaceArr), $saveName);
  186. }
  187. /**
  188. * 上传文件
  189. * @param ?string $saveName
  190. * @param int $adminId
  191. * @param int $userId
  192. * @return array
  193. * @throws Throwable
  194. */
  195. public function upload(?string $saveName = null, int $adminId = 0, int $userId = 0): array
  196. {
  197. if (empty($this->file)) {
  198. throw new Exception(__('No files have been uploaded or the file size exceeds the upload limit of the server'));
  199. }
  200. $this->checkSize();
  201. $this->checkMimetype();
  202. $this->checkIsImage();
  203. $params = [
  204. 'topic' => $this->topic,
  205. 'admin_id' => $adminId,
  206. 'user_id' => $userId,
  207. 'url' => $this->getSaveName(),
  208. 'width' => $this->fileInfo['width'] ?? 0,
  209. 'height' => $this->fileInfo['height'] ?? 0,
  210. 'name' => substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
  211. 'size' => $this->fileInfo['size'],
  212. 'mimetype' => $this->fileInfo['type'],
  213. 'storage' => 'local',
  214. 'sha1' => $this->fileInfo['sha1']
  215. ];
  216. $attachment = new Attachment();
  217. $attachment->data(array_filter($params));
  218. $res = $attachment->save();
  219. if (!$res) {
  220. $attachment = Attachment::where([
  221. ['sha1', '=', $params['sha1']],
  222. ['topic', '=', $params['topic']],
  223. ['storage', '=', $params['storage']],
  224. ])->find();
  225. } else {
  226. $this->move($saveName);
  227. }
  228. return $attachment->toArray();
  229. }
  230. public function move($saveName = null): File
  231. {
  232. $saveName = $saveName ?: $this->getSaveName();
  233. $saveName = '/' . ltrim($saveName, '/');
  234. $uploadDir = substr($saveName, 0, strripos($saveName, '/') + 1);
  235. $fileName = substr($saveName, strripos($saveName, '/') + 1);
  236. $destDir = root_path() . 'public' . str_replace('/', DIRECTORY_SEPARATOR, $uploadDir);
  237. return $this->file->move($destDir, $fileName);
  238. }
  239. }