protected function beforeValidate() { if (empty($this->instanceId) && empty($this->tmpId)) { $this->addError('instanceId', 'Не указан instanceId.'); } $file = CUploadedFile::getInstance($this, 'file'); if ($file) { foreach (self::$deniedExtensions as $ext) { if (strpos($file->getName(), '.' . $ext) !== false) { $this->addError('file', 'Файл имеет запрещенное расширение.'); return false; } } } $objectParameter = $this->getObjectParameter(); //если есть ограничение по типу файлов, то нужно добавить в валидатор if ($objectParameter && ($addParam = $objectParameter->getAdditionalParameter())) { $types = FileExtension::getExtensionsByType($addParam); $validators = $this->getValidators('file'); if (isset($validators[0]) && $validators[0] instanceof CFileValidator) { $validators[0]->types = $types; } } return parent::beforeValidate(); }
public function actionUpload() { //$path = Yii::app()->baseUrl."/uploads"; $model = new XUploadForm(); if (!isset($this->path)) { $this->path = realpath(Yii::app()->basePath . "/../uploads"); } if (!is_dir($this->path)) { throw new CHttpException(500, "{$this->path} does not exists."); } else { if (!is_writable($this->path)) { throw new CHttpException(500, "{$this->path} is not writable."); } } if ($model->validate()) { $model->file = CUploadedFile::getInstance($model, 'file'); $model->mime_type = $model->file->getType(); $model->size = $model->file->getSize(); $model->name = $model->file->getName(); $path = $this->path . "/" . Yii::app()->session['userId']; $model->file->saveAs($path . $model->name); $pageImage = new Pages(); $pageImage->user_id = Yii::app()->user->userId; $pageImage->image = $model->name; $pageImage->save(); Yii::app()->session['pageId'] = $pageImage->id; Yii::app()->session['imageName'] = $model->name; echo json_encode(array("name" => $model->name, "type" => $model->mime_type, "size" => $model->getReadableFileSize())); /* $user_id = Yii::app()->session['userId']; if ($model->file->getType() != 'image/jpeg' && $model->file->getType() !='image/png' && $model->file->getType() !='image/bmp' && $model->file->getType() != 'image/jpg') { echo "Invalid File Type, only jpg allowed"; } else { $profile = UserProfile::model()->find('user_id=:id', array('id' => Yii::app()->session['userId'])); $old_pic = $profile['photo']; if ((strpos($old_pic, "h")) === 0) { $profile->photo = Yii::app()->session['userId'] . '_' . $model->name; $profile->save(); $model->file->saveAs($path . '_' . $model->name); //Yii::app()->user->setFlash('success', "Upload Picture Successfully"); } elseif ((strpos($old_pic, $profile['user_id'])) === 0) { unlink(realpath(Yii::app()->getBasePath() . "/../images/uploads") . "/" . urldecode($old_pic)); $profile->photo = Yii::app()->session['userId'] . '_' . $model->name; $profile->save(); $model->file->saveAs($path . '_' . $model->name); //Yii::app()->user->setFlash('success', "Upload Picture Successfully"); } else { //unlink(realpath(Yii::app()->getBasePath()."/../images/uploads")."/".urldecode($old_pic)); //$profile->photo = Yii::app()->session['userId'] . '_' . $model->name; //$profile->save(); //$model->file->saveAs($path . '_' . $model->name); //Yii::app()->user->setFlash('success', "Upload Picture Successfully"); } echo json_encode(array("name" => $model->name,"type" => $model->mime_type,"size"=> $model->getReadableFileSize())); //echo "hogya hai "; //$this->redirect(Yii::app()->baseUrl.'/index.php/user/userprofile/'.$user_id); //echo '<script type="text/javascript">window.top.href = "' . Yii::app()->baseUrl . '/index.php/user/userprofile/' . $user_id . '"; </script>'; } } else { /*echo CVarDumper::dumpAsString($model->getErrors()); Yii::log("XUploadAction: ".CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "application.extensions.xupload.actions.XUploadAction"); throw new CHttpException(500, "Could not upload file"); */ //echo $this->redirect(Yii::app()->baseUrl); //echo "<script type='text/javascript'>alert('chage');</script>"; } /* $model=new Image; if(isset($_POST['Image'])) { $model->attributes=$_POST['Image']; $model->image=CUploadedFile::getInstance($model,'image'); $fileTempName=$model->thumbnail->tempName; $fileName=$model->thumbnail->name; if($model->save()) { $userId=Yii::app()->session['userId']; $upload_dir=realpath(getcwd()).'/images/uploads/'; move_uploaded_file($fileTempName, "$upload_dir/$userId".'_'."$fileName"); // $model->image->saveAs('path/to/localFile'); // redirect to success page return; } return; }*/ //$this->render('create', array('model'=>$model)); }
public function actionUpload() { Yii::import("xupload.models.XUploadForm"); //Here we define the paths where the files will be stored temporarily $path = Yii::app()->getBasePath() . "/../"; $publicPath = 'http://img.yincart.com'; // // if (!file_exists($path)) { // mkdir($path, 0777, true); // } // $ymd = date("Ymd"); // $path .= $ymd . '/'; // if (!file_exists($path)) { // mkdir($path, 0777, true); // } //This is for IE which doens't handle 'Content-type: application/json' correctly header('Vary: Accept'); if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) { header('Content-type: application/json'); } else { header('Content-type: text/plain'); } //Here we check if we are deleting and uploaded file if (isset($_GET["_method"])) { if ($_GET["_method"] == "delete") { if ($_GET["file"][0] !== '.') { $file = $path . $_GET["file"]; if (is_file($file)) { unlink($file); } } echo json_encode(true); } } else { $model = new XUploadForm(); $upload = new FileUpload(array($model, 'file'), 'upload/groupon'); if (!$upload->isNull()) { $model->mime_type = $upload->instance->getType(); $model->size = $upload->instance->getSize(); $model->name = $upload->instance->getName(); if ($model->validate()) { $filename = $upload->save(); // } // } // $model->file = CUploadedFile::getInstance($model, 'file'); //We check that the file was successfully uploaded // if ($model->file !== null) { //Grab some data // $model->mime_type = $model->file->getType(); // $model->size = $model->file->getSize(); // $model->name = $model->file->getName(); //(optional) Generate a random name for our file // $filename = date("YmdHis") . '_' . rand(10000, 99999); // $filename .= "." . $model->file->getExtensionName(); // $filename = $ymd . '/' . $filename; // if ($model->validate()) { //Move our file to our temporary dir // $model->file->saveAs($path . $filename); // chmod($path . $filename, 0777); //here you can also generate the image versions you need //using something like PHPThumb //Now we need to save this path to the user's session if (Yii::app()->user->hasState('images')) { $userImages = Yii::app()->user->getState('images'); } else { $userImages = array(); } $userImages[] = array("path" => $path . $filename, "thumb" => $path . $filename, "filename" => $filename, "url" => $publicPath . '/' . $filename, 'size' => $model->size, 'mime' => $model->mime_type, 'name' => $model->name); Yii::app()->user->setState('images', $userImages); //Now we need to tell our widget that the upload was succesfull //We do so, using the json structure defined in // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup echo json_encode(array(array("name" => $model->name, "type" => $model->mime_type, "size" => $model->size, "url" => $publicPath . '/' . $filename, "thumbnail_url" => $publicPath . '/' . "{$filename}", "delete_url" => $this->createUrl("upload", array("_method" => "delete", "file" => $filename)), "delete_type" => "POST"))); } else { //If the upload failed for some reason we log some data and let the widget know echo json_encode(array(array("error" => $model->getErrors('file')))); Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"); } } else { throw new CHttpException(500, "Could not upload file"); } } }