The example in this article describes how Yii uses the activeFileField control to upload 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 introduces 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 $htmlOpti ( ))
(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) Then, set the form in the view:
<div> <?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> <?php echo '图片预览' ?> <?php echo '<img src="http://www.XXXX.com/'.$model->BookImg.'"/>'; ?> </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 need to change it.
(5) 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 help you design PHP programs based on the Yii framework. Helps.
The above introduces how Yii uses the activeFileField control to upload files and pictures, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.