UploadController.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. $mainId = $this->mainId;
  25. if (intval($mainId) == 0) {
  26. Yii::error('------- lose token -------');
  27. noticeUtil::push('save-file 无token进行上传文件');
  28. return;
  29. }
  30. $shopId = $this->shopId;
  31. $month = date("Ym");
  32. $date = date("d");
  33. $path = dirUtil::getImgUploadDir() . "/wxAvatar/{$mainId}/{$shopId}/{$month}/{$date}/";
  34. // 检查目录是否存在,如果不存在则尝试创建。
  35. // 使用 @ 抑制 mkdir 在目录已存在时(并发导致)的 warning。
  36. // 如果 mkdir 失败,则再次检查目录是否存在,以区分是并发创建成功还是真的创建失败。
  37. if (!is_dir($path) && !@mkdir($path, 0700, true) && !is_dir($path)) {
  38. throw new \yii\web\ServerErrorHttpException("目录 '{$path}' 创建失败。");
  39. }
  40. $preFileName = stringUtil::uniqueFileName();
  41. $newFile = $preFileName . ".jpg";
  42. $fullPathFile = $path . $newFile;
  43. if (move_uploaded_file($file['tmp_name'], $fullPathFile)) {
  44. $img = "{$uploadPath}/wxAvatar/{$mainId}/{$shopId}/{$month}/{$date}/" . $newFile;
  45. oss::uploadImage($img, $fullPathFile);
  46. $data = business::formatUploadImg($img);
  47. $data['shortUrl'] = $img;
  48. $data['smallShortUrl'] = $img . "?x-oss-process=image/resize,l_200";
  49. util::success($data, 'ok');
  50. } else {
  51. util::fail('fail');
  52. }
  53. }
  54. }