Esempio n. 1
0
 public function actionUploadImage()
 {
     try {
         $productId = intval(Yii::app()->request->getPost('product_id'));
         $file = CUploadedFile::getInstanceByName('Filedata');
         // 检查上传文件
         if ($file instanceof CUploadedFile == false) {
             throw new Exception('无法识别上传文件');
         }
         // 检查尺寸
         list($width, $height, $type, $attr) = getimagesize($file->tempName);
         if (empty($width) || empty($height)) {
             throw new Exception($file->name . ' 无法识别图片');
         }
         if ($width < 380) {
             throw new Exception($file->name . ' 尺寸不符合要求,请上传宽大于或等于 380 像素的图片');
         }
         // 保存原图
         $fileName = md5($file->tempName . uniqid()) . '.' . $file->extensionName;
         $filePath = Helper::mediaPath(Product::UPLOAD_ORIGINAL_IMAGE_PATH . $fileName, FRONTEND);
         $file->saveAs($filePath, false);
         // 裁切大图
         require_once 'Image.php';
         $image = new Image($filePath);
         $image->resize(380, 380)->save(Helper::mediaPath(Product::UPLOAD_LARGE_IMAGE_PATH . $fileName, FRONTEND));
         // 裁切缩略图
         $image = new Image($filePath);
         $image->resize(80, 80)->save(Helper::mediaPath(Product::UPLOAD_THUMBNAIL_IMAGE_PATH . $fileName, FRONTEND));
         // 入库
         $model = new ProductImage();
         $model->product_id = $productId;
         $model->file_name = $file->name;
         $model->image_path = $fileName;
         $model->sort_order = 0;
         $model->is_released = 1;
         $model->save();
         echo CJSON::encode(array('result' => true, 'product_image_id' => $model->primaryKey, 'product_id' => $productId, 'thumbnail_image_url' => $model->getThumbnailImageUrl(), 'file_name' => $model->file_name));
     } catch (Exception $e) {
         echo CJSON::encode(array('result' => false, 'message' => $e->getMessage()));
     }
 }