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, ));
}

方法二:

在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_7522019b01014zno.html

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

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

yii中上传图片及文件的更多相关文章

  1. ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案

    摘要: ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案 在struts2应用中使用ueditor富文本编辑器上传图片或者附件时,即使配置 ...

  2. sau交流学习社区--在element-ui中新建FormData对象组合上传图片和文件的文件对象,同时需要携带其他参数

    今天有一个坑,同时要上传图片和文件,而且图片要展示缩略图,文件要展示列表. 我的思路是: 首先,只上传附件照片,这个直接看ele的官方例子就行,不仅仅上传附件照片,还同时上传其他参数. 然后,再做上传 ...

  3. Yii中的错误及异常处理

    Yii中的错误及异常处理 Yii已经默认已经在CApplication上实现了异常和错误的接管,这是通过php的set_exception_handler, set_error_handler实现的. ...

  4. Spring中MultipartHttpServletRequest实现文件上传

    Spring中MultipartHttpServletRequest实现文件上传 转贴自:http://my.oschina.net/nyniuch/blog/185266 实现图片上传  用户必须能 ...

  5. yii 中引入js 和css 的方式

    在yii中 我们需要引入css 和 js 的时候,yii 自身有需要的类. 当我在views 视图层中引入css 和 js , <?php Yii::app()->clientScript ...

  6. yii中的自定义组件

    yii中的自定义组件(组件就是一些自定义的公用类) 1.在项目目录中的protected/components/Xxxx.php 2.在Xxxx.php中定义一个类,类名必须与文件名相同 3.控制器中 ...

  7. Javascript and AJAX with Yii(在yii 中使用 javascript 和ajax)

    英文原文:http://www.yiiframework.com/wiki/394/javascript-and-ajax-with-yii /*** http://www.yiiframework. ...

  8. yii 中设置提示成功信息,错误提示信息,警告信息

    方法一: <?php Yii::app()->user->setFlash(‘success’,”Data saved!”); 设置键值名为success的临时信息.在getFlas ...

  9. [Yii][RBAC]Yii中应用RBAC完全指南

    开端筹办 Yii供给了强大的设备机制和很多现成的类库.在Yii中应用RBAC是很简单的,完全不须要再写RBAC代码.所以筹办工作就是,打开编辑器,跟我来. 设置参数.建树数据库 在设备数组中,增长以下 ...

随机推荐

  1. Mysql DOC阅读笔记

    Mysql DOC阅读笔记 转自我的Github Speed of SELECT Statements 合理利用索引 隔离调试查询中花费高的部分,例如函数调用是在结果集中的行执行还是全表中的行执行 最 ...

  2. 【转】关于oracle with as用法

    原文链接:关于oracle with as用法 with as语法–针对一个别名with tmp as (select * from tb_name) –针对多个别名with   tmp as (se ...

  3. 基于ActiveMQ的点对点收发消息

    ActiveMQ是apache的一个开源消息引擎.可以作为即通引擎或者消息中间件引擎. 准备 下载ActiveMQ http://activemq.apache.org/download.html 进 ...

  4. Java中的TCP/UDP网络通信编程

    127.0.0.1是回路地址,用于测试,相当于localhost本机地址,没有网卡,不设DNS都可以访问. 端口地址在0~65535之间,其中0~1023之间的端口是用于一些知名的网络服务和应用,用户 ...

  5. 面试题:实现LRUCache::Least Recently Used的缩写,意思是最近最少使用,它是一种Cache替换算法

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  6. mac 布置 git仓库服务器

    创建管理员账户 例如:git 使用git账户登录 开启git账户的远程登陆 创建仓库文件夹 sudo git --bare init 更改配置文件 cd /Users/userName/project ...

  7. glibc 安装( version `GLIBC_2.14' not found")

    在ubuntu上编译的东西 拿到CentOS 下运行 提示 :“/lib64/libc.so.6: version `GLIBC_2.14' not found” 原因是ubuntu上用的libc 版 ...

  8. 简单的网页采集程序(ASP.NET MVC4)

    因为懒人太多,造成现在网页数据采集非常的流行,我也来写个简单的记录一下. 之前写了MVC的基本框架的搭建随笔,后面因为公司太忙,个人感情问题:(,导致不想写了,就写了两篇给删除了,现在就搁浅了, 本人 ...

  9. 查看用户列表在Linux

    Linux下查看用户列表   原文地址:http://xiaod.in/read.php?77 俺的centos vps上面不知道添加了多少个账户,今天想清理一下,但是以前还未查看过linux用户列表 ...

  10. JavaScript 语言基础知识点总结

    网上找到的一份JavaScript 语言基础知识点总结,还不错,挺全面的. (来自:http://t.cn/zjbXMmi @刘巍峰 分享 )