在Yii里上传文件通常使用yii\web\UploadedFile类,它把每个上传的文件封装成UploadedFile对象。结合yii\webgets\ActiveForm和models,你可以轻松实现安全的上传文件机制。
创建模型
namespaceapp\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model{
/**
*@var UploadedFile file attribute
*/
public $file;
/**
*@return array the validation rules
*/
public function rules(){
return[
[['file'],'file'],
];
}
}
imageFile属性用于接收上传的文件实例。它对应一条file验证规则.
渲染文件输出
use yii\widgets\ActiveForm;
?>
['enctype' =>'multipart/form-data']]) ?>
= $form->field($model,'imageFile')->fileInput() ?>
需要注意的是要记得在表单选项里加入enctype属性以确保文件能被正常上传。fileInput()方法会渲染一个标签,让用户可以选择一个文件上传。
视图和模型的连接
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class ReleseController extends Controller{
publicfunctionactionUpload(){
if ($_FILES) {
$model_file->file = UploadedFile::getInstance($model_file, 'file');
$filename = $model_file->file->name;
$model_file->file->name = iconv("utf-8", "gb2312", $filename);//这里是处理中文的问题,非中文不需要
if ($model_file->file && $model_file->validate()) {
$rootPath = "../../file/uploads/"; //定义上传的根目录
$ext = $model_file->file->extension; //获取文件的后缀(*格式*)
$randName = time() . rand(1000, 9999) . "." . $ext; //重新编译文件名称
$model_file->file->saveAs($rootPath . $randName); //调用内置封装类**执行上传
}
$model->cover =$randName; //存入数据库
}
}
}
上传多个文件
创建模型
在file验证规则里增加一个maxFiles选项,用以限制一次上传文件的最大数量
namespaceapp\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model{
/**
*@var UploadedFile file attribute
*/
public $file;
/**
*@return array the validation rules
*/
public function rules(){
return[
[['file'],'file','maxFiles'=>4],
];
}
}
视图
把multiple选项添加到fileInput()函数调用里,这样文件输入控件就可以接收多个文件。
use yii\widgets\ActiveForm;
?>
['enctype' =>'multipart/form-data']]) ?>
= $form->field($model,'imageFiles[]')->fileInput(['multiple'=>true,'accept'=>'image/*']) ?>
视图与模型连接
在控制器的 action 方法中,你应该调用 UploadedFile::getInstances 而不是 UploadedFile::getInstance() 来把 UploadedFile 实例数组赋值给 UploadForm::imageFiles。
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class ReleseController extends Controller{
publicfunctionactionUpload(){
if ($_FILES) {
$model_file->file = UploadedFile::getInstances($model_file, 'file');
$filename = $model_file->file->name;
$model_file->file->name = iconv("utf-8", "gb2312", $filename);//这里是处理中文的问题,非中文不需要
if ($model_file->file && $model_file->validate()) {
$rootPath = "../../file/uploads/"; //定义上传的根目录
$ext = $model_file->file->extension; //获取文件的后缀(*格式*)
$randName = time() . rand(1000, 9999) . "." . $ext; //重新编译文件名称
$model_file->file->saveAs($rootPath . $randName); //调用内置封装类**执行上传
}
$model->cover =$randName; //存入数据库
}
}
}