| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- <?php
- namespace mall\controllers;
- use bizMall\custom\classes\CustomClass;
- use common\components\business;
- use common\components\dirUtil;
- use common\components\noticeUtil;
- use common\components\oss;
- use common\components\stringUtil;
- use Yii;
- use common\components\util;
- class UploadController extends BaseController
- {
- public function actionSaveFile()
- {
- $uploadPath = 'uploads';
- // 对上传的文件进行多文件夹管理
- $rootPath = Yii::$app->request->post('rootPath');
- if (!empty($rootPath) && in_array($rootPath, oss::ROOT_PATHS)) {
- $uploadPath = $rootPath;
- }
- $file = $_FILES['file'];
- if (!is_uploaded_file($file['tmp_name'])) {
- util::fail('please upload img');
- }
- $userId = $this->userId;
- if (empty($userId)) {
- noticeUtil::push("上传时没有找到userId", '15280215347');
- }
- $month = date("Ym");
- $date = date("d");
- $path = dirUtil::getImgUploadDir() . "/wxAvatar/$userId/{$month}/{$date}/";
- // 检查目录是否存在,如果不存在则尝试创建。
- // 使用 @ 抑制 mkdir 在目录已存在时(并发导致)的 warning。
- // 如果 mkdir 失败,则再次检查目录是否存在,以区分是并发创建成功还是真的创建失败。
- if (!is_dir($path) && !@mkdir($path, 0700, true) && !is_dir($path)) {
- throw new \yii\web\ServerErrorHttpException("目录 '{$path}' 创建失败。");
- }
- $preFileName = stringUtil::uniqueFileName();
- $newFile = $preFileName . ".jpg";
- $fullPathFile = $path . $newFile;
- if (move_uploaded_file($file['tmp_name'], $fullPathFile)) {
- $img = "{$uploadPath}/wxAvatar/$userId/{$month}/{$date}/" . $newFile;
- oss::uploadImage($img, $fullPathFile);
- $data = business::formatUploadImg($img);
- $actType = Yii::$app->request->get('actType');
- if ($actType == 'saveAvatar') {
- $user = $this->user;
- $user->avatar = $img;
- $user->save();
- CustomClass::updateByCondition(['userId' => $userId], ['avatar' => $img]);
- }
- $data['shortUrl'] = $img;
- $data['smallShortUrl'] = $img . "?x-oss-process=image/resize,l_200";
- util::success($data, 'ok');
- } else {
- util::fail('fail');
- }
- }
- }
|