Yii uses the CForm class (Formbuilder) to upload a file model (model)
First, you need a file Upload model:FileUpload. php
1234567891011121314151617 |
? Php classFileUploadextendsCFormModel {public $ image;/*** @ return array validation rules for model attributes. */publicfunctionrules () {returnarray (// note you wont need a safe rule here array ('image', 'file', 'allowempty '=> true, 'types' => 'jpg, jpeg, gif, png '),);}} |
Note:> for more information about verification rules, see Reference: Model rules validation.
Array used for CForm
Create an array for CForm:UploadForm. php
1234567891011121314151617181920212223242526 |
'Upload your image', 'bubuckets' => array ('enablesype '=> 'multipart/form-data ',), 'elements' => array ('image' => array ('type' => 'File ',),), 'buttons' => array ('reset' => array ('type' => 'Reset', 'label' => 'Reset ',), 'submit '=> array ('type' => 'Submit', 'label' => 'upload ',),),); |
View File)
Create a view file:Upload. php
1234567891011 |
User-> hasFlash ('success'):?> User-> getFlash ('success');?> Image Upload |
Controller)
Add controller and action ):
123456789101112131415161718 |
Submitted ('submit ') & $ form-> validate () {$ form-> model-> image = CUploadedFile: getInstance ($ form-> model, 'image ');//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Do something with your image here //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! Yii: app ()-> user-> setFlash ('success', 'File uploaded'); $ this-> redirect (array ('upload '));} $ this-> render ('upload', array ('form' => $ form ));}} |
The best method here is to perform some operations on the image in your FileUpload model. Note: You do not needFileUpload: imageAssign values, but you can provide a method to access it to achieve a strong model (model) to simplify the controller ).