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 |
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 name, tempName, type, size 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 |
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中上传图片及文件的更多相关文章
- ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案
摘要: ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案 在struts2应用中使用ueditor富文本编辑器上传图片或者附件时,即使配置 ...
- sau交流学习社区--在element-ui中新建FormData对象组合上传图片和文件的文件对象,同时需要携带其他参数
今天有一个坑,同时要上传图片和文件,而且图片要展示缩略图,文件要展示列表. 我的思路是: 首先,只上传附件照片,这个直接看ele的官方例子就行,不仅仅上传附件照片,还同时上传其他参数. 然后,再做上传 ...
- Yii中的错误及异常处理
Yii中的错误及异常处理 Yii已经默认已经在CApplication上实现了异常和错误的接管,这是通过php的set_exception_handler, set_error_handler实现的. ...
- Spring中MultipartHttpServletRequest实现文件上传
Spring中MultipartHttpServletRequest实现文件上传 转贴自:http://my.oschina.net/nyniuch/blog/185266 实现图片上传 用户必须能 ...
- yii 中引入js 和css 的方式
在yii中 我们需要引入css 和 js 的时候,yii 自身有需要的类. 当我在views 视图层中引入css 和 js , <?php Yii::app()->clientScript ...
- yii中的自定义组件
yii中的自定义组件(组件就是一些自定义的公用类) 1.在项目目录中的protected/components/Xxxx.php 2.在Xxxx.php中定义一个类,类名必须与文件名相同 3.控制器中 ...
- Javascript and AJAX with Yii(在yii 中使用 javascript 和ajax)
英文原文:http://www.yiiframework.com/wiki/394/javascript-and-ajax-with-yii /*** http://www.yiiframework. ...
- yii 中设置提示成功信息,错误提示信息,警告信息
方法一: <?php Yii::app()->user->setFlash(‘success’,”Data saved!”); 设置键值名为success的临时信息.在getFlas ...
- [Yii][RBAC]Yii中应用RBAC完全指南
开端筹办 Yii供给了强大的设备机制和很多现成的类库.在Yii中应用RBAC是很简单的,完全不须要再写RBAC代码.所以筹办工作就是,打开编辑器,跟我来. 设置参数.建树数据库 在设备数组中,增长以下 ...
随机推荐
- jsonp 使用示例
客户端: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>< ...
- C# Linq To DataTable 分组统计 DEMO
DataTable dt = SQLLayer.Get工作量统计(beginDate, endDate); var querySum = from t in dt.AsEnum ...
- gulp最佳实践(包含js,css,html预编译,合并,压缩,浏览器自动刷新)
gulp是基于流的自动化构建工具官方网址:http://www.gulpjs.com.cn/ 一.安装需要的模块 1.新建package.json,输入下面的内容 { "name" ...
- hadoop2.610集群配置(包含HA和Hbase )
.修改Linux主机名2.修改IP3.修改主机名和IP的映射关系######注意######如果你们公司是租用的服务器或是使用的云主机(如华为用主机.阿里云主机等)/etc/hosts里面要配置的是内 ...
- Swift与Objective-C的兼容“黑魔法”:@objc和Dynamic
Cocoa框架早已烙上了不可磨灭的OC印记,而无数的第三方库都是用OC写成的,这些积累无论是谁都不能小觑.苹果采取了允许开发者在同一个项目中同时使用Swift和OC进行开发的做法,但要想实现互通,又需 ...
- ASP.NET MVC轻教程 Step By Step 1 ——入门
使用ASP.NET MVC有一段时间了,本人还是非常喜欢ASP.NET MVC这个框架模式的.在经历了WebForm复杂粗暴的做法后,自然感觉简洁优雅的MVC清新可人,只不过WebForm和MVC的设 ...
- Visual Studio Code扩展
Visual Studio Code扩展 注:本文提到的代码示例下载地址>How to create a simple extension for VS Code VS Code 是微软推出的一 ...
- [原博客] BZOJ 1257 [CQOI2007] 余数之和
题目链接题意: 给定n,k,求 ∑(k mod i) {1<=i<=n} 其中 n,k<=10^9. 即 k mod 1 + k mod 2 + k mod 3 + … + k mo ...
- hdu 1269
强连通分量题,用tarjin算法: 这是一道很简单的tarjin算法题,基本上就是套模板: 贴代码: #include<cstdio> #include<vector> #in ...
- 【JavaScript】JavaScript函数的参数
要访问js函数中传入的所有参数,可以使用特殊的arguments变量.但是虽然可以像访问数组一样从arguments变量中读取参数,但arguments并非真正的数组.例如,arguments没有pu ...