This article describes the example of yii using the activeFileField control to implement the method of uploading files and pictures. Share it with everyone for your reference, the details are as follows:
The yii framework provides the activeFileField control to complete the operation of uploading files (including uploading images, of course). The following describes how to use yii's activeFileField.
1. Function prototype:
Copy code The code is as follows: public static string activeFileField(CModel $model, string $attribute, array $htmlOptions=array ( ))
2. Call example:
(1) First, set the form. This step must be done. Set the form to 'multipart/form-data'. For details, please see my:
<?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'books-form', 'enableAjaxValidation'=>false, 'htmlOptions'=>array('enctype'=>'multipart/form-data'), )); ?>
(2) Next, set in the form under view:
<div class="row"> <?php echo $form->labelEx($model,'BookImg'); ?> <?php echo CHtml::activeFileField($model,'BookImg'); ?> <?php echo $form->error($model,'BookImg'); ?> </div>
(3) If you want to preview the picture, please note that you can add this paragraph:
<div class="row"> <?php echo '图片预览' ?> <?php echo '<img src="http://www.XXXX.com/'.$model->BookImg.'" style="width:200px;height:300px;"/>'; ?> </div>
(4) Finally, you need to add the following to the control class:
if($model->save()) { $image=CUploadedFile::getInstance($model,'BookImg'); if (is_object($image) && get_class($image)==='CUploadedFile') { $image->saveAs("D:/aaa/aa.jpg");//路径必须真实存在,并且如果是linux系统,必须有修改权限 } $this->redirect(array('view','id'=>$model->BookId)); }
Please note: This is used when adding. If you modify it, you will need to change it.
(5) It is restricted that the uploaded files must be pictures, and there is also a limit on the size of the pictures, then please go to the rules in the model layer and add this sentence:
array('BookImg', 'file','allowEmpty'=>true, 'types'=>'jpg, gif, png', 'maxSize'=>1024 * 1024 * 1, // 1MB 'tooLarge'=>'The file was larger than 1MB. Please upload a smaller file.', )
I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.