zoukankan      html  css  js  c++  java
  • yii中上传图片及文件

    Yii 提供了 CUploadedFile 来上传文件,比如图片,或者文档。 

    官方关于这个类的介绍 :

    http://www.yiichina.com/api/CUploadedFile

     

    CUploadedFile

    system.web
    继承 class CUploadedFile » CComponent
    源自 1.0
    版本 $Id: CUploadedFile.php 3515 2011-12-28 12:29:24Z mdomba $
    源码 framework/web/CUploadedFile.php
    CUploadedFile represents the information for an uploaded file. 

    Call getInstance 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 nametempNametypesize and error.

    公共属性

    隐藏继承属性

    属性类型描述定义在
    error integer Returns an error code describing the status of this file uploading. CUploadedFile
    extensionName string the file extension name for name. CUploadedFile
    hasError boolean whether there is an error with the uploaded file. CUploadedFile
    name string the original name of the file being uploaded CUploadedFile
    size integer the actual size of the uploaded file in bytes CUploadedFile
    tempName string the path of the uploaded file on the server. CUploadedFile
    type string the MIME-type of the uploaded file (such as "image/gif"). CUploadedFile

    方法一:
     
     实现上传文件,要用到MVC三个层面。 

    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应该设置为: multupart/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, ));
        }

    方法二:

    在protectedcomponents下新建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_7522019b01014zno.html

    http://hi.baidu.com/32641469/item/a25a3e16334232cd39cb30bc

    http://seo.njxzc.edu.cn/seo650

  • 相关阅读:
    出现灾难性Bug:Vista RTM跳票内幕曝光
    微软官方反间谍流氓软件WindowsDefender
    在Windows上玩转Mono/Linux
    使用信息架构视图访问数据库元数据
    BPM 与 SOA的演进与展望
    使用Microsoft® .NET Framework 3.0 and Visual Studio® 2005开发的免费课程
    bootstrap源码学习与示例:bootstrapdropdown
    bootstrap源码学习与示例:bootstrapalert
    我的MVVM框架 v3教程——todos例子
    我的MVVM框架 v3教程——类名切换
  • 原文地址:https://www.cnblogs.com/imxiu/p/3439466.html
Copyright © 2011-2022 走看看