Yii2使用表单上传文件的实例代码
程序员文章站
2024-03-11 22:58:43
yii2用表单上传文件经常用到的,该怎样上传呢?
1、单个文件上传
首先建立一个模型models/uploadform.php,内容如下
namespac...
yii2用表单上传文件经常用到的,该怎样上传呢?
1、单个文件上传
首先建立一个模型models/uploadform.php,内容如下
namespace app\models; use yii\base\model; use yii\web\uploadedfile; /** * uploadform is the model behind the upload form. */ class uploadform extends model { /** * @var uploadedfile file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file'], ]; } }
再建立一个视图文件,内容如下
<?php use yii\widgets\activeform; ?> <?php $form = activeform::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($model, 'file')->fileinput() ?> <button>submit</button> <?php activeform::end() ?>
最后建立控制器文件,内容如下
namespace app\controllers; use yii; use yii\web\controller; use app\models\uploadform; use yii\web\uploadedfile; class sitecontroller extends controller { public function actionupload() { $model = new uploadform(); if (yii::$app->request->ispost) { $model->file = uploadedfile::getinstance($model, 'file'); if ($model->file && $model->validate()) { $model->file->saveas('uploads/' . $model->file->basename . '.' . $model->file->extension); } } return $this->render('upload', ['model' => $model]); } }
注意这里我们没有用model->load(...),而是用了uploadedfile::getinstance(...)。区别是后者不会执行$model->validate(),所以需要手动的去执行$model->validate()来检验数据的合法性。如果检验通过了,上传的文件保存在uploads文件夹下,即web目录下的uploads里。
一些可选的配置选项
上传文件不能为空
public function rules() { return [ [['file'], 'file', 'skiponempty' => false], ]; }
上传类型,不仅可以根据扩展名检验,还可以根据文件的内容进行检验
public function rules() { return [ [['file'], 'file', 'extensions' => 'jpg, png', 'mimetypes' => 'image/jpeg, image/png',], ]; }
2、多文件上传
如果你想一次上传多个文件,只需调节几个参数就可以达到目的
model:
class uploadform extends model { /** * @var uploadedfile|null file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file', 'maxfiles' => 10], // <--- here! ]; } }
view:
<?php use yii\widgets\activeform; $form = activeform::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?= $form->field($model, 'file[]')->fileinput(['multiple' => true]) ?> <button>submit</button> <?php activeform::end(); ?>
与单文件上传不同的是下面这句
$form->field($model, 'file[]')->fileinput(['multiple' => true])
controller:
namespace app\controllers; use yii; use yii\web\controller; use app\models\uploadform; use yii\web\uploadedfile; class sitecontroller extends controller { public function actionupload() { $model = new uploadform(); if (yii::$app->request->ispost) { $model->file = uploadedfile::getinstances($model, 'file'); if ($model->file && $model->validate()) { foreach ($model->file as $file) { $file->saveas('uploads/' . $file->basename . '.' . $file->extension); } } } return $this->render('upload', ['model' => $model]); } }
这样就可以实现多文件上传了。
参考
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: spring声明式事务解析