Upload.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. /**
  5. * 前端上传接口
  6. * @ApiWeigh (90)
  7. */
  8. class Upload extends Api
  9. {
  10. protected $noNeedLogin = '';//都需要登录
  11. /**
  12. * 上传头像
  13. *
  14. * @ApiTitle (上传头像)
  15. * @ApiSummary (上传头像上传头像)
  16. * @ApiMethod (POST)
  17. * @ApiHeaders (name="user-token", type="string", required=true, description="请求的Token")
  18. * @ApiRoute (/api/upload/upload)
  19. * @ApiParams (name="user_id", type="int", required=true, description="用户user_id")
  20. * @ApiParams (name="token", type="int", required=true, description="请求的Token")
  21. * @ApiParams (name="file", type="file", required=true, description="图片文件")
  22. * @ApiReturn ({
  23. "code": 1,
  24. "msg": "ok",
  25. "time": "1604727883",
  26. "data": "/uploads/images/202011/5fa6344bbadaa.jpg"
  27. })
  28. */
  29. public function upload()
  30. {
  31. $file_file='images';
  32. $dir = ROOT_PATH . 'public' . DS . 'uploads/'.$file_file.'/'.date('Ym').'/';
  33. if (!file_exists($dir)) {
  34. mkdir($dir, 0700,true);
  35. }
  36. $files = $_FILES;
  37. $imageArr = Array();
  38. foreach ($files as $file) {
  39. $imageName = $file['name'];
  40. //后缀名
  41. $ext = strtolower(substr(strrchr($imageName,'.'),1));
  42. //保存文件名
  43. $fileName = uniqid();
  44. $tmp = $file['tmp_name'];
  45. //保存 = 路径 + 文件名 + 后缀名
  46. $imageSavePath = $dir.$fileName.'.'.$ext;
  47. $info = move_uploaded_file($tmp, $imageSavePath);
  48. if ($info) {
  49. $path = '/uploads/'.$file_file.'/'.date('Ym').'/'.$fileName.'.'.$ext;
  50. array_push($imageArr, $path);
  51. }
  52. }
  53. //最终生成的字符串路径
  54. $imagePathStr = implode(',', $imageArr);
  55. //return $imagePathStr;
  56. $this->result('ok', $imagePathStr, 1);
  57. }
  58. }