Esempio n. 1
0
 /**
  * Process upload of thumbnail
  *
  * @return mixed the uploaded thumbnail instance
  */
 public function upload()
 {
     // get the uploaded file instance. for multiple file uploads
     // the following data will return an array (you may need to use
     // getInstances method)
     $thumbnails = UploadedFile::getInstances($this, 'thumbnail');
     $isThumbnail = true;
     // if no thumbnail was uploaded abort the upload
     if (empty($thumbnails)) {
         return false;
     }
     // generate store the source file name
     $storage_path = Yii::$app->params['uploadStoragesPath'];
     $path = implode("/", [$storage_path, Yii::$app->formatter->asQuoteTabelName(self::tableName())]);
     if (!is_dir($path)) {
         mkdir($path);
     }
     foreach ($thumbnails as $thumbnail) {
         $image = new Image();
         $image->target = Yii::$app->formatter->asQuoteTabelName(self::tableName());
         $image->target_id = $this->getId();
         $image->is_thumbnail = $isThumbnail ? Image::_IS_THUMBNAIL : Image::_NOT_THUMBNAIL;
         $image->type = $image->type;
         $image->status = Image::STATUS_ACTIVE;
         if ($image->save(false)) {
             $thumbnail->saveAs($storage_path . "/" . $image->getFullPath());
             $isThumbnail = false;
         }
     }
 }
 public function actionImagesUpload()
 {
     $out = [];
     $images = \yii\web\UploadedFile::getInstancesByName('images');
     $isThumbnail = true;
     $target = Yii::$app->request->post('target');
     $target_id = Yii::$app->request->post('target_id');
     if (empty($images)) {
         echo Json::encode(['error' => Yii::t('message', 'No files found for upload.')]);
         // or you can throw an exception
         return;
         // terminate
     }
     $storage_path = Yii::$app->params['uploadStoragesPath'];
     $path = implode("/", [$storage_path, $target]);
     if (!is_dir($path)) {
         mkdir($path);
     }
     foreach ($images as $image) {
         $img = new Image();
         $img->target = $target;
         $img->target_id = $target_id;
         $img->is_thumbnail = $isThumbnail ? Image::_IS_THUMBNAIL : Image::_NOT_THUMBNAIL;
         $img->type = $image->type;
         $img->status = Image::STATUS_ACTIVE;
         if ($img->save(false)) {
             $image->saveAs($storage_path . "/" . $img->getFullPath());
             $isThumbnail = false;
             echo Json::encode(['success' => Yii::t('message', 'Up files (:path) success !.')]);
         } else {
             echo Json::encode(['error' => Yii::t('message', 'Up files (:path) error !.')]);
         }
     }
 }