[转]yii上传图片

转载自: http://hi.baidu.com/wastorode/blog/item/4a59b44128487b31cefca3ff.html

First declare an attribute to store the file name in the model class (either a form model or an active record model). Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name.

class Item extends CActiveRecord
{
    public $image;
    // ... other attributes

    public function rules()
    {
        return array(
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
    }
}
复制代码

Then, in the controller class define an action method to render the form and collect user-submitted data.

class ItemController extends CController
{
    public function actionCreate()
    {
        $model=new Item;
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->save())
            {
                $model->image->saveAs('path/to/localFile');
                // redirect to success page
            }
        }
        $this->render('create', array('model'=>$model));
    }
}
复制代码

Finally, create the action view and generate a file upload field.

<? php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>
...
<?php echo CHtml::activeFileField($model, 'image'); ?>
...
<?php echo CHtml::endForm(); ?>
复制代码

转自cookbook的帖子http://www.yiiframework.com/doc/cookbook/2/

 

 

???谢谢分享学习了,这里的Item必须是数据库里的表吗?比如我的上传字段只是注册里的一项,应该怎么弄谢谢,请指教

---------------------------------------------------------------------

Item是表名,比如我需要上传图片的一个字段是pic,那么我们可以直接获取这个字段,$_POST['Item']['pic'],这样就可以了!

 

???请问,controllerj里的$model->image->saveAs方法是自己写的还是?为什么我这样写:Call to a member function saveAs() on a non-object,报这个?

-----------------------------------------------------------------------

这个错误是没有对象.必须先实例化CUploadedFile

$model->image=CUploadedFile::getInstance($model,'image'); 
//实例化CUploadedFile,此时$model->image为CUploadedFile的一个对象.
if($model->save())
{
        $model->image->saveAs('path/to/localFile');
        //saveAs是CUploadedFile的一个方法.
        // redirect to success page
}


???谢谢,那saveAs里的路径直接写可以吗?文档上就写保存上传图片的路径,比如我想放在项目路径下的upload文件夹,可不可以写 成:saveAs(Yii::app()->basePath.'\\upload\\tmp\\'.$img->name);

但我这样写报:move_uploaded_file(E:\www\register\protected\upload\123.jpg) [<a href='function.move-uploaded-file'>function.move-uploaded-file</a>]: failed to open stream: No such file or directory

-----------------------------------------------------------------------------

因为不会自动创建目录,所以你必须保证上传图片的目录存在!

 

???

activeFileField() 如何实现只能图片上传:

model 里的规则
public $image; //别忘了声明
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
....
array('image', 'file','allowEmpty'=>true ,
'types'=>'jpg, gif, png',
'maxSize'=>1024 * 1024 * 10, // 10MB
'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
),

);
}

 

http://www.yiiframework.com/forum/index.php?/topic/6329-activefilefield-%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%8F%AA%E8%83%BD%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0/

 

2.

需要特别注意的是,form的开头必须指定enctype。如:

<?php echo CHtml::beginForm(”,’post’,array(’enctype’=>’multipart/form-data’)); ?>

否则得是不行的啊。这块我曾忘记了,搞半天搞不成才发现我的form少定义了enctype了。

enctype 属性 — 代表HTML表单数据的编码方式

enctype 属性取值:  application/x-www-form-urlencoded — 窗体数据被编码为名称/值对.这是标准的编码格式. multipart/form-data — 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分. text/plain — 窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符

view中:

<?php echo CHtml::activeFileField($model,’uploads’); ?>
model里rules:
array(’uploads’,'file’,'types’=>’doc,rar,zip’,'maxSize’=>’8000000′),
controller里:
$file = CUploadedFile::getInstance($model,’uploads’);
即可取得上 传的文件,然后通过
$file->saveAs($_SERVER['DOCUMENT_ROOT'].”/uploads/”.$fname);
即可保存文件。

 

作者: qiang

 

我的例子:

public function actionCreate()
{
   $model=new Post;
   if(isset($_POST['Post']))
   {
    $model->attributes=$_POST['Post'];
    //取得上传的文件
    $model->thumb=CUploadedFile::getInstance($model,'thumb');      
    if($model->save()){
     $model->thumb->saveAs(Yii::app()->params['uploadPath'] . $model->thumb);
     $this->redirect(array('admin',)); 
    }   
   }

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

 

Model:

EROR: thumb cannot be blank

I use this:(unset)

if($this->thumb=='') unset($this->thumb);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值