yiiに画像とファイルをアップロードする

18832 ワード

Yiiは、画像やドキュメントなどのCUploadefileを提供しています。 
公式にはこの類について紹介されています。
http://www.yiichina.com/api/CUploadedFile
 
CUploadefile
すべてのカバン | 
属性 | 
方法
包みをつくる
system.web
引き継ぐ
class CUploaded File』  CComponent
源を発する
1.0
バージョン
$Id:CUploadedFile.php 3515 2010-11-28 12:29:24 Z mdommmmbaドル
ソース
frame ework/web/CUploadedFile.php
CUploadefile represents the information for an upladed file. 
コール 
get Instance to retrieve the instance of an uploaded file,and then use 
saveAs to save it on the server.You may also query other information about the file,including 
name、 
tempName、 
タイプ、 
size and 
error.
共通の属性
相続のプロパティを隠す
属性
タイプ
説明
定義は
error
インテグ
Returns an error code describing the status of this file uloading.
CUploadefile
extension Name
ストリングス
the file extension name for  name.
CUploadefile
ハスエルロ
bollan
whether there is an error with the up loaded file.
CUploadefile
name
ストリングス
the original name of the file being uplloaded
CUploadefile
size
インテグ
the actual size of the up loaded file in bytes
CUploadefile
tempName
ストリングス
the path of the up loaded file on the server.
CUploadefile
タイプ
ストリングス
the MIME-type of the up loaded file(such as「イメージ/gif」)
CUploadefile
方法1:
 
 アップロードファイルを実現するには、MVCの3つのレベルが必要です。 
1、モデルレベルM(User.php)は、フィールドをrulesメソッドにfile属性として設定します。
            array('url',

                'file',    //   file  

                'allowEmpty'=>false, 

                'types'=>'jpg,png,gif,doc,docx,pdf,xls,xlsx,zip,rar,ppt,pptx',   //       

                'maxSize'=>1024*1024*10,    //      ,    php.ini        

                'tooLarge'=>'    10M,    !     10M   !'

            ),

            //array('imgpath','file','types'=>'jpg,gif,png','on'=>'insert'),

            array('addtime', 'length', 'max'=>10),
2、ビュー層View(upimg.php)は、CHtmlを使用する必要があります。:activeFileFieldは選択ファイルのbuttonを生成します。アップロードファイルであることに注意して、このラベルのenctypeは、multip/form-dataに設定します。 
詳細は:http://www.yiichina.com/api/CHtml#activeFileField-detail
<?php $form=$this->beginWidget('CActiveForm', array(

    'id'=>'link-form',

    'enableAjaxValidation'=>false,

    /**

     * activeFileField()                  。

     *   ,        ‘enctype’   ‘multipart/form-data’。

     *       ,           $_FILES[$name]    (    PHP documentation).

     */

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

)); ?>



    <div class="row">

        <?php echo $form->labelEx($model,'url'); ?>

        <?php if($model->url){ echo '<img src="/'.$model->url.'" width="20%"/>';} ?>

        <?php echo CHtml::activeFileField($model,'url'); ?>

        <?php echo $form->error($model,'url'); ?>

    </div>



    <div class="row buttons">

        <?php echo CHtml::submitButton('  '); ?>

    </div>

<?php $this->endWidget(); ?>
3、制御層C(UserController.php)
    //        

    public function actionUpimg()

    {

        $model = new User;



        // Uncomment the following line if AJAX validation is needed

        // $this->performAjaxValidation($model);



        if (isset($_POST['User'])) {

            $model->attributes = $_POST['User'];

            $file = CUploadedFile::getInstance($model, 'url'); //    CUploadedFile   

            //if (is_object($file) && get_class($file) === 'CUploadedFile') { //          

            if ($file) { //          

                $newimg = 'url_' . time() . '_' . rand(1, 9999) . '.' . $file->extensionName;

                //               ,extensionName         

                $file->saveAs('assets/uploads/user/' . $newimg); //     

                $model->url = 'assets/uploads/user/' . $newimg;

            }

            $model->addtime = time();



            if ($model->save()){

                $this->redirect(array('view', 'id' => $model->id)); 

            }

        }



        $this->render('upimg', array('model' => $model, ));

    }
 
方法二:
protected\componentsでUploadImg.phpファイルを新規作成します。
<?php

/**

 *      ,           

 * 

 * @author 

 */

class UploadImg

{

    public static function createFile($upload, $type, $act, $imgurl = '')

    {

        //    

        if (!empty($imgurl) && $act === 'update') {

            $deleteFile = Yii::app()->basePath . '/../' . $imgurl;

            if (is_file($deleteFile))

                unlink($deleteFile);

        }

        

        //    

        $uploadDir = Yii::app()->basePath . '/../uploads/' . $type . '/' . date('Y-m', time());

        self::recursionMkDir($uploadDir);

        //               ,extensionName         

        $imgname = time() . '-' . rand() . '.' . $upload->extensionName;

        //      

        $imageurl = '/uploads/' . $type . '/' . date('Y-m', time()) . '/' . $imgname;

        //      

        $uploadPath = $uploadDir . '/' . $imgname;

        if ($upload->saveAs($uploadPath)) {

            return $imageurl;

        } else {

            return false;

        }

    }

    

    //    

    private static function recursionMkDir($dir)

    {

        if (!is_dir($dir)) {

            if (!is_dir(dirname($dir))) {

                self::recursionMkDir(dirname($dir));

                mkdir($dir, '0777');

            } else {

                mkdir($dir, '0777');

            }

        }

    }

}
制御層C(UserController.php)は、
    //        

    public function actionUpimg()

    {

        $model = new User;

        

        if (isset($_POST['User'])) {

            $model->attributes = $_POST['User'];

            $upload = CUploadedFile::getInstance($model, 'url'); //    CUploadedFile   

            if ($upload) { //          

                $model->url = UploadImg::createFile($upload, 'User', 'upimg');    

            } 

            

            $model->addtime = time();   



            if ($model->save()) {

                $this->redirect(array('view', 'id' => $model->id));

            }

        }

        $this->render('upimg', array('model' => $model, ));

    }
 
参照ページ:
http://blog.csdn.net/littlebearwmx/article/details/8573102
http://wuhai.blog.51cto.com/blog/2023916/953300
http://blog.sina.com.cn/s/blog_7522009 b 010114 zno.
http://hi.baidu.com/32641469/item/a25a3e16334232cd39cb30bc
http://seo.njxzc.edu.cn/seo650