1. CUploadedFile implements single file upload
(Recommended tutorial: yii framework)
(1) First, in the model The class declares an attribute to store the file name (either form model or active record model). Also declare a file validation rule to ensure that uploaded files have the specified extension.
class Item extends CActiveRecord { public $image; // ... other attributes public function rules() { return array( array('image', 'file', 'types'=>'jpg, gif, png'), ); } }
(2) Then, define an action method in the controller class to collect the data submitted by the user
class ItemController extends CController { public function actionCreate() { $model=new Item; if(isset($_POST['Item'])) { $model->attributes=$_POST['Item']; $model->image=CUploadedFile::getInstance($model,'image'); if($model->save()) { $model->image->saveAs('path/to/localFile'); // redirect to success page } } $this->render('create', array('model'=>$model)); } }
(recommended related tutorials: php graphic tutorial)
(3) Finally, create the action view and generate an uploaded field.
<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?> ... <?php echo CHtml::activeFileField($model, 'image'); ?> ... <?php echo CHtml::endForm(); ?>
2. CUploadedFile implements multiple file uploads
Method: view view code:
for($i=0;$i<3;$i++){ //echo $form->fileField($model,'xiangguan_tupian[]').'<br/>';//这种方法不行 //echo CHtml::activeFileField($model,'xiangguan_tupian[]');//这种也不行 //echo CHtml::fileField('xiangguan_tupian[]','',array('id'=>'xiangguan_tupian'.$i)).' ';//这种也不行 echo CHtml::activeFileField($model,'xiangguan_tupian[]',array('id'=>'xiangguan_tupian'.$i)); } ?>
controller controller side: The upload is processed.
(Learning video recommendation:
php video tutorial$model=new Info; // echo '<hr><br>'; $obj_array=CUploadedFIle::getInstances($model,'xiangguan_tupian'); //注意这里不是getInstance而是getInstances多了个s,这样得到的是一个包含CUploadedFile对象的数组 //print_r($obj_array); foreach($obj_array as $k=>$v){ $v->saveAs(Yii::app()->basePath.'/'.$k.'_test.'.$v->getExtensionName()); }
3. Use sendFile() to download files
CUploadedFile::getInstance(); // 返回的是一个CUploadedFile对象, CUploadeFile::getInstanceByName(); //返回的是一个CUploadedFile对象 CUploadedFile::getInstances() //返回的是一个值为CUploadedFile对象的数组 CUploadedFile::getInstancesByName(); //返回的是一个值为CUploadedFile对象的数组
The above is the detailed content of Use the yii framework to implement file upload and download functions. For more information, please follow other related articles on the PHP Chinese website!