UploadTrait.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. <?php
  2. namespace App\Traits;
  3. use App\Services\Ueditor\CrawlerAction;
  4. use App\Services\Ueditor\ListAction;
  5. use App\Services\Ueditor\UploadAction;
  6. use App\Services\UploaderService;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Str;
  9. use phpDocumentor\Reflection\Types\Boolean;
  10. use Txj\Elastic\Facades\ES;
  11. use Illuminate\Http\JsonResponse;
  12. use Illuminate\Http\UploadedFile;
  13. use Illuminate\Support\Facades\Request;
  14. trait UploadTrait
  15. {
  16. /**
  17. * 是否保存到数据库
  18. *
  19. * @var bool
  20. */
  21. public bool $isSaveToDb = true;
  22. /**
  23. * 保存的表
  24. *
  25. * @var string
  26. */
  27. public string $table = 'media_list';
  28. public bool $isRename = true; // 是否需要重命名
  29. /**
  30. * 上传图片
  31. */
  32. public function img()
  33. {
  34. $type = Request::post('type');
  35. $group_id = Request::post('group_id');
  36. if (empty($type)) {
  37. return responseMessage(2001, '请选择类型');
  38. }
  39. $upload = Request::file('file');
  40. if ($upload) {
  41. return $this->getUploadFilePath($upload, 'img', $group_id, ['png', 'jpg', 'jpeg', 'gif'], 2048000);
  42. } else {
  43. return responseMessage(2002, '上传失败,请重试!');
  44. }
  45. }
  46. /**
  47. * 文件上传
  48. *
  49. * @return JsonResponse
  50. */
  51. public function file()
  52. {
  53. $type = Request::post('type');
  54. $group_id = Request::post('group_id');
  55. if (empty($type)) {
  56. return responseMessage(2001, '请选择类型');
  57. }
  58. $this->isRename = false;
  59. $upload = Request::file('file');
  60. if ($upload) {
  61. return $this->getUploadFilePath($upload, 'file', $group_id, [], 300*1024*1000);
  62. } else {
  63. return responseMessage(2005, '上传失败,请重试!');
  64. }
  65. }
  66. /**
  67. * 上传
  68. *
  69. * @param UploadedFile $file
  70. * @param string $type
  71. * @param int $group_id
  72. * @param array $isAllowFileExtension
  73. * @param int $maxFileSize
  74. * @return JsonResponse
  75. */
  76. private function getUploadFilePath(UploadedFile $file, string $type, int $group_id, array $isAllowFileExtension = [], int $maxFileSize = 2048000): JsonResponse
  77. {
  78. $fileName = $file->getClientOriginalName();
  79. $size = $file->getSize();
  80. // 2.是否符合文件类型 getClientOriginalExtension 获得文件后缀名
  81. $fileExtension = $file->getClientOriginalExtension();
  82. if ($isAllowFileExtension && !in_array($fileExtension, $isAllowFileExtension)) {
  83. return responseMessage(3001, '该文件类型不支持上传!');
  84. }
  85. // 3.判断大小是否符合 2M
  86. $tmpFile = $file->getRealPath();
  87. if (filesize($tmpFile) >= $maxFileSize) {
  88. return responseMessage(3002, '该文件大小,超过允许的最大值!');
  89. }
  90. $upload_dir = $this->getUploadDir($type);
  91. $disk_dir = public_path('static/' . $upload_dir);
  92. if (!file_exists($disk_dir) || !is_dir($disk_dir)) {
  93. @mkdir($disk_dir, 0777, true);
  94. }
  95. // todo 是否需要重命名 通过软件可以对图片压缩
  96. if ($this->isRename) {
  97. $file_name = md5(microtime()) . '.' . $fileExtension;
  98. } else {
  99. $file_name = $fileName;
  100. }
  101. $file->move($disk_dir, $file_name);
  102. $path = '/static/' . $upload_dir . $file_name;
  103. switch ($type) {
  104. case 'img':
  105. $imgType = 1;
  106. break;
  107. case 'video':
  108. $imgType = 2;
  109. break;
  110. case 'audio':
  111. $imgType = 3;
  112. break;
  113. case 'file':
  114. $imgType = 4;
  115. break;
  116. default:
  117. return responseMessage(3003, '该文件类型不支持上传!');
  118. }
  119. return $this->saveDb([
  120. 'group_id' => $group_id,
  121. 'type' => $imgType,
  122. 'extension' => $fileExtension,
  123. 'size' => $size,
  124. 'filename' => $fileName,
  125. 'path' => $path
  126. ]);
  127. }
  128. /**
  129. * 上传视频
  130. *
  131. * @return JsonResponse
  132. */
  133. public function video(): JsonResponse
  134. {
  135. $type = Request::post('type');
  136. $group_id = Request::post('group_id');
  137. if (empty($type)) {
  138. return responseMessage(2001, '请选择类型');
  139. }
  140. $upload = Request::file('file');
  141. if ($upload) {
  142. return $this->getUploadFilePath($upload, 'video', $group_id, ['mp4', 'mov'], 2048000);
  143. } else {
  144. return responseMessage(2005, '上传失败,请重试!');
  145. }
  146. }
  147. /**
  148. * 上传音频
  149. */
  150. public function audio(): JsonResponse
  151. {
  152. $type = Request::post('type');
  153. $group_id = Request::post('group_id');
  154. if (empty($type)) {
  155. return responseMessage(2001, '请选择类型');
  156. }
  157. $upload = Request::file('audio');
  158. if ($upload) {
  159. return $this->getUploadFilePath($upload, 'audio', $group_id, ['mp3'], 2048000);
  160. } else {
  161. return responseMessage(2005, '上传失败,请重试!');
  162. }
  163. }
  164. /**
  165. * 上传图片base64
  166. *
  167. * @return String
  168. * @throws \Exception
  169. */
  170. public function upBase64()
  171. {
  172. $requestData = Request::all();
  173. $group_id = $requestData['group_id'] ?? '';
  174. $base64Data = $requestData['img'] ?? '';
  175. if (empty($base64Data)) {
  176. return responseMessage(2001, '上传失败');
  177. }
  178. //截取字符串
  179. $base64Data = preg_replace('/data:image\/png;base64,/is', '', $base64Data);
  180. $img = base64_decode($base64Data);
  181. if (empty($img)) {
  182. return responseMessage(2002, '上传失败');
  183. }
  184. $upload_dir = $this->getUploadDir('img');
  185. $disk_dir = public_path('static/' . $upload_dir);
  186. if (!file_exists($disk_dir) || !is_dir($disk_dir)) {
  187. @mkdir($disk_dir, 0777, true);
  188. }
  189. //移动文件
  190. $file_name = md5(microtime()) . '.png';
  191. $filePath = $disk_dir . '/' . $file_name;
  192. $path = $upload_dir . $file_name;
  193. if (!file_put_contents($filePath, $img)) { //移动失败
  194. return responseMessage(2003, '上传失败,请重试!');
  195. } else { //移动成功
  196. $imgType = 1;
  197. $fileExtension = 'png';
  198. return $this->saveDb([
  199. 'group_id' => intval($group_id),
  200. 'type' => $imgType,
  201. 'extension' => $fileExtension,
  202. 'size' => strlen($img),
  203. 'filename' => $file_name,
  204. 'path' => $path
  205. ]);
  206. }
  207. }
  208. /**
  209. * 裁剪图片
  210. */
  211. public function crop()
  212. {
  213. $requestData = Request::all();
  214. $imgId = $requestData['id'] ?? '';
  215. $x = $requestData['x'] ?? 0;
  216. $y = $requestData['y'] ?? 0;
  217. $w = $requestData['w'] ?? '';
  218. $h = $requestData['h'] ?? '';
  219. if (empty($imgId)) {
  220. return responseMessage(2001, '图片不存在!');
  221. }
  222. if (empty($w) || empty($h)) {
  223. return responseMessage(2002, '参数错误!');
  224. }
  225. //获取图片信息
  226. $imgInfo = ES::table('media_list')->getEsInfo($imgId);
  227. if (empty($imgInfo)) {
  228. return responseMessage(2003, '图片不存在!');
  229. }
  230. $path = $imgInfo['path'];
  231. if (file_exists(public_path('static/' . $path))) {
  232. $upload = new UploaderService(
  233. '',
  234. [
  235. 'filePath' => '/static' . $imgInfo['path'],
  236. 'thumb' => [
  237. [
  238. 'x' => $x,
  239. 'y' => $y,
  240. 'width' => $w,
  241. 'height' => $h,
  242. ]
  243. ]
  244. ], 'crop');
  245. if (isset($upload->thumbs[0])) {
  246. $info = $upload->thumbs[0];
  247. $imgType = 1;
  248. $path = $info['path'] ? '/' . trim($info['path'], '/static') : '';
  249. return $this->saveDb([
  250. 'group_id' => $imgInfo['group_id'],
  251. 'type' => $imgType,
  252. 'extension' => $imgInfo['extension'],
  253. 'size' => $info['metadata']['file.FileSize'] ?? 0,
  254. 'filename' => $imgInfo['filename'],
  255. 'path' => $path
  256. ]);
  257. } else {
  258. return responseMessage(2004, '操作失败,请重试!!');
  259. }
  260. } else {
  261. return responseMessage(2005, '图片不存在!');
  262. }
  263. }
  264. /**
  265. * 获取当前用户的唯一标识
  266. *
  267. * @param $type
  268. * @return string
  269. */
  270. private function getUploadDir($type)
  271. {
  272. return '/upload/' . substr($this->siteInfo['mid'], 2, 8) . '/' . $type . '/' . mt_rand(0, 99) . '/';
  273. }
  274. #################################################################################################################
  275. ##### 百度上传 #####################################################################################################
  276. #################################################################################################################
  277. public function ueditor()
  278. {
  279. $config_path = config_path('ueditor.json');
  280. $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config_path)), true);
  281. $action = Request::input('action');
  282. // 动态设置图片前缀,显示全路径
  283. $static_url = config('app.asset_url');
  284. $CONFIG = array_merge($CONFIG, [
  285. 'imageUrlPrefix' => $static_url,
  286. 'scrawlUrlPrefix' => $static_url,
  287. 'snapscreenUrlPrefix' => $static_url,
  288. 'catcherUrlPrefix' => $static_url,
  289. 'videoUrlPrefix' => $static_url,
  290. 'fileUrlPrefix' => $static_url,
  291. 'imageManagerUrlPrefix' => $static_url,
  292. 'fileManagerUrlPrefix' => $static_url,
  293. ]);
  294. switch ($action) {
  295. case 'config':
  296. $result = json_encode($CONFIG);
  297. break;
  298. /* 上传图片 */
  299. case 'uploadimage':
  300. /* 上传涂鸦 */
  301. case 'uploadscrawl':
  302. $result = (new UploadAction($CONFIG, $action))->doUpload();
  303. //保存到数据库
  304. $this->saveToDb(1, 'media_list', $result);
  305. break;
  306. /* 上传视频 */
  307. case 'uploadvideo':
  308. $result = (new UploadAction($CONFIG, $action))->doUpload();
  309. //保存到数据库
  310. $this->saveToDb(2, 'media_list', $result);
  311. break;
  312. /* 上传文件 */
  313. case 'uploadfile':
  314. $result = (new UploadAction($CONFIG, $action))->doUpload();
  315. //保存到数据库
  316. $this->saveToDb(4, 'media_list', $result);
  317. break;
  318. /* 列出图片 */
  319. case 'listimage':
  320. /* 列出文件 */
  321. case 'listfile':
  322. $result = (new ListAction($CONFIG, $action))->doList();
  323. break;
  324. /* 抓取远程文件 */
  325. case 'catchimage':
  326. $result = (new CrawlerAction($CONFIG, $action))->doCrawler();
  327. break;
  328. default:
  329. $result = json_encode(array(
  330. 'state' => '请求地址出错'
  331. ));
  332. break;
  333. }
  334. /* 输出结果 */
  335. if (isset($_GET["callback"])) {
  336. if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
  337. echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
  338. } else {
  339. echo json_encode(array(
  340. 'state' => 'callback参数不合法'
  341. ));
  342. }
  343. } else {
  344. echo $result;
  345. }
  346. die();
  347. }
  348. /**
  349. * 编辑器上传保存
  350. *
  351. * @param $type
  352. * @param $alias
  353. * @param $result
  354. * @return JsonResponse|void
  355. */
  356. private function saveToDb($type, $alias, $result)
  357. {
  358. $result = json_decode($result, true);
  359. if (empty($result) || !is_array($result)) {
  360. return;
  361. }
  362. return $this->saveDb([
  363. 'group_id' => 0,
  364. 'type' => $type,
  365. 'extension' => $result['original'] ?? '',
  366. 'size' => $result['size'] ?? 0,
  367. 'filename' => $result['original'] ?? '',
  368. 'path' => $result['url'] ?? ''
  369. ]);
  370. }
  371. /**
  372. * 保存到数据库
  373. *
  374. * @param $data
  375. * @return JsonResponse
  376. */
  377. private function saveDb($data): JsonResponse
  378. {
  379. if ($this->isSaveToDb) {
  380. $data['mid'] = Str::random(12);
  381. $data['created_at'] = time();
  382. $data['updated_at'] = time();
  383. // 保存数据库
  384. $isSuccess = DB::table($this->table)->insert($data);
  385. if ($isSuccess) {
  386. return responseMessage(1001, '恭喜你,上传成功!', $data['filename']);
  387. } else {
  388. return responseMessage(2003, '上传失败,请重试!');
  389. }
  390. } else {
  391. return responseMessage(1001, '恭喜你,上传成功!!', $data['filename']);
  392. }
  393. }
  394. }