在Yii中验证并保存上传的ajax图像


validating and save an uploaded ajax image in Yii

我需要通过一个ajax请求发送一个图像到服务器,它通过刚刚好
在我的控制器中,我可以使用$_FILES["image"]对它进行操作。
但是我需要在保存图像之前验证它。
在Yii中,这可以通过这样做来实现

$file = CUploadedFile::getInstance($model,'image');
if($model->validated(array('image'))){
    $model->image->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user_thumb/' . $model->username.'.'.$model->photo->extensionName);
}

但问题是我没有$model,我只有$_FILES["image"],现在我应该用什么来代替$model ??
有没有其他的方法,我可以验证和保存文件,而不创建一个模型,只是通过使用$_FILES["image"] ?
感谢这个很棒的社区…:)

上传的方式有很多。我想给你其中一个。

1。您需要为您的图像创建模型。

class Image extends CActiveRecord {
    //method where need to specify validation rules
    public function rules()
    {
        return [
            ['filename', 'length', 'max' => 40],
            //other rules
        ];
    }
    //this function allow to upload file
    public function doUpload($insName)
    {
        $file = CUploadedFile::getInstanceByName($insName);
        if ($file) {
            $file->saveAs(Yii::getPathOfAlias('webroot').'/upload/user_thumb/'.$this->filename.$file->getExtensionName());
        } else {
            $this->addError('Please, select at least one file'); // for example
        }
    }   
}

2。现在,需要创建控制器,您将在其中执行所有操作。

class ImageController extends CController {
    public function actionUpload()
    {
        $model = new Image();
        if (Yii::app()->request->getPost('upload')) {
            $model->filename = 'set filename';
            $insName = 'image'; //if you try to upload from $_FILES['image']
            if ($model->validate() && $model->doUpload($insName)) {
                //upload is successful
            } else {
                //do something with errors
                $errors = $model->getErrors();
            }
        }
    }    
}

在某些情况下,创建模型可能是多余的。

$_FILE超变量是HTTP机制的一部分。

你可以使用本地PHP函数move_uploaded_file()来处理拷贝

   $fileName = "/uploads/".myimage.jpg";
   unlink($fileName);
   move_uploaded_file($_FILES['Filedata']['tmp_name'], $fileName);

但是,您失去了使用提供额外功能和检查(例如文件类型和文件大小限制)的库的细节。