AttachmentController.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Http\Controllers\V1;
  3. use Illuminate\Http\Request;
  4. use App\Helper\AttachmentHelper;
  5. use Illuminate\Support\Facades\Validator;
  6. class AttachmentController extends Controller
  7. {
  8. use AttachmentHelper;
  9. /**
  10. * * 可能出现的错误代码:
  11. * 200 SAVE_USER_FAILED 保存用户数据失败
  12. * 201 ATTACHMENT_MKDIR_FAILED 创建附件目录失败
  13. * 202 ATTACHMENT_UPLOAD_INVALID 上传附件文件无效
  14. * 203 ATTACHMENT_SAVE_FAILED 保存附件失败
  15. * 204 ATTACHMENT_MOVE_FAILED 移动附件失败
  16. * 205 ATTACHMENT_DELETE_FAILED 删除附件文件失败
  17. * 206 ATTACHMENT_RECORD_DELETE_FAILED 删除附件记录失败
  18. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  19. * 1101 INCORRECT_VERIFY_CODE 输入验证码错误
  20. * 1105 USER_DOES_NOT_EXIST 用户不存在
  21. * 1200 ATTACHMENT_UPLOAD_FAILED 附件上传失败
  22. * 1201 ATTACHMENT_SIZE_EXCEEDED 附件大小超过限制
  23. * 1202 ATTACHMENT_MIME_NOT_ALLOWED 附件类型不允许
  24. * 1203 ATTACHMENT_NOT_EXIST 附件不存在.
  25. *
  26. * @return \Illuminate\Http\JsonResponse
  27. */
  28. public function upload(Request $request)
  29. {
  30. try {
  31. $validator = Validator::make(
  32. $request->all(),
  33. [
  34. 'tag' => 'required|alpha_dash',
  35. ],
  36. [
  37. 'tag.required' => 'tag必填',
  38. 'tag.alpha_dash' => 'tag只能为字母数字中/下划线',
  39. ]
  40. );
  41. if ($validator->fails()) {
  42. throw new \Exception($validator->messages()->first());
  43. }
  44. $result = $this->uploadAttachment($request, $request->post('file'), $request->post('tag'), 10 * 1024 * 1024, [
  45. 'image/jpeg',
  46. 'image/png',
  47. 'image/gif',
  48. 'video/mp4',
  49. ]);
  50. } catch (\Exception $exception) {
  51. return $this->error($exception->getMessage());
  52. }
  53. return $this->success(['file' => $result], 0, trans('api.UPLOAD_SUCCESS'));
  54. }
  55. /**
  56. * @return \Illuminate\Http\JsonResponse
  57. * parse_url($url);
  58. * array (
  59. * 'scheme' => 'https',
  60. * 'host' => 'zhengda.oss-cn-chengdu.aliyuncs.com',
  61. * 'path' => '/api_avatar/2022-07/14/1271657787068220714.jpeg',
  62. * )
  63. */
  64. public function delete(Request $request)
  65. {
  66. $picUrl = $request->pic_url;
  67. if (empty($picUrl)) {
  68. return $this->error('路径必填!');
  69. }
  70. $arr = parse_url($picUrl);
  71. $path = substr($arr['path'], 1);
  72. $result = $this->deleteAttachment($path);
  73. if ($result) {
  74. return $this->success();
  75. }
  76. return $this->error();
  77. }
  78. }