2011-06-24 18:18:52 1 评论 Yii 1.0 Boy.Lee

Yii 1.0 上传并重命名文件

{Controller}

$model=new Map;
//check is the user decide to upload Description Image Three, then do different operate
if (@!empty($_FILES['Map']['name']['description_img_3'])){
  $model->description_img_3 = $model->generateRandomName(2);
  if ($model->validate(array('description_img_3'))){
    $model->uploaded_description_img_3 = CUploadedFile::getInstance($model, 'description_img_3');
    $model->uploaded_description_img_3->saveAs(Yii::app()->basePath.'/../map_img/'.$model->description_img_3);
  }
}else {
  $model->description_img_3 = '';
}

 

{Method :: GenerateRandomName}

public function generateRandomName($intType)
{
    $strFileName = '';
    switch ($intType) {
        case 0: //map cover image
        $strFileName.='mapCover_';
        $strEnd = '.jpg';
        break;

        case 1: //map description swf
        $strFileName.='mapMovie_';
        $strEnd = '.swf';
        break;

        case 2: //map description image
        $strFileName.='mapImage_';
        $strEnd = '.jpg';
        break;

        case 3: //map version file
        $strFileName.='mapFile_';
        $strEnd = '.rar';
        break;

        default://default name
        $strFileName.='mapUpload_';
        $strEnd = '.unknown';
        break;
    }

    $strFileName.=time().'_';

    $strFileName.=$this->randStr();

    $strFileName.=$strEnd;

    return $strFileName;
}

function randStr($len=6,$format='ALL_WORD') {
     switch($format) {
     case 'ALL_WORD':
     $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; break;
     case 'ALL':
     $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break;
     case 'CHAR':
     $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
     case 'NUMBER':
     $chars='0123456789'; break;
     default :
     $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
     break;
     }

     mt_srand((double)microtime()*1000000*getmypid());
     $password="";
     while(strlen($password)<$len)
        $password.=substr($chars,(mt_rand()%strlen($chars)),1);
     return $password;
 }

 

{View} 

 echo $form->labelEx($model,'description_img_3');
 echo $form->fileField($model,'description_img_3',array('size'=>60,'maxlength'=>1500));
 echo $form->error($model,'description_img_3');

 

{View :: Form Define}

$form=$this->beginWidget('CActiveForm', array(
	'id'=>'map-form',
	'enableAjaxValidation'=>false,
	'htmlOptions' =>array('enctype'=>"multipart/form-data" )
)); 

非常容易是吧? ^&^

PS: 在需要上传文件的时候必须为表单设置multipart/form-data 属性否则上传会失败

'htmlOptions' =>array('enctype'=>"multipart/form-data" )