UploadController.php 2.3 KB

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