UploadController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace mall\controllers;
  3. use bizMall\custom\classes\CustomClass;
  4. use common\components\business;
  5. use common\components\dirUtil;
  6. use common\components\noticeUtil;
  7. use common\components\oss;
  8. use common\components\stringUtil;
  9. use Yii;
  10. use common\components\util;
  11. class UploadController extends BaseController
  12. {
  13. public function actionSaveFile()
  14. {
  15. $uploadPath = 'uploads';
  16. // 对上传的文件进行多文件夹管理
  17. $rootPath = Yii::$app->request->post('rootPath');
  18. if (!empty($rootPath) && in_array($rootPath, oss::ROOT_PATHS)) {
  19. $uploadPath = $rootPath;
  20. }
  21. $file = $_FILES['file'];
  22. if (!is_uploaded_file($file['tmp_name'])) {
  23. util::fail('please upload img');
  24. }
  25. $userId = $this->userId;
  26. if (empty($userId)) {
  27. noticeUtil::push("上传时没有找到userId", '15280215347');
  28. }
  29. $month = date("Ym");
  30. $date = date("d");
  31. $path = dirUtil::getImgUploadDir() . "/wxAvatar/$userId/{$month}/{$date}/";
  32. // 检查目录是否存在,如果不存在则尝试创建。
  33. // 使用 @ 抑制 mkdir 在目录已存在时(并发导致)的 warning。
  34. // 如果 mkdir 失败,则再次检查目录是否存在,以区分是并发创建成功还是真的创建失败。
  35. if (!is_dir($path) && !@mkdir($path, 0700, true) && !is_dir($path)) {
  36. throw new \yii\web\ServerErrorHttpException("目录 '{$path}' 创建失败。");
  37. }
  38. $preFileName = stringUtil::uniqueFileName();
  39. $newFile = $preFileName . ".jpg";
  40. $fullPathFile = $path . $newFile;
  41. if (move_uploaded_file($file['tmp_name'], $fullPathFile)) {
  42. $img = "{$uploadPath}/wxAvatar/$userId/{$month}/{$date}/" . $newFile;
  43. oss::uploadImage($img, $fullPathFile);
  44. $data = business::formatUploadImg($img);
  45. $actType = Yii::$app->request->get('actType');
  46. if ($actType == 'saveAvatar') {
  47. $user = $this->user;
  48. $user->avatar = $img;
  49. $user->save();
  50. CustomClass::updateByCondition(['userId' => $userId], ['avatar' => $img]);
  51. }
  52. $data['shortUrl'] = $img;
  53. $data['smallShortUrl'] = $img . "?x-oss-process=image/resize,l_200";
  54. util::success($data, 'ok');
  55. } else {
  56. util::fail('fail');
  57. }
  58. }
  59. }