yii2 文件上传

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了yii2 文件上传相关的知识,希望对你有一定的参考价值。

直接贴代码了

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

先新建一个model文件 UploadForm.php

  内容:   

<?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‘],
];
}
}

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

控制器层内容:

  

function actionIndexadv(){
$request = Yii::$app->request;
$model = new UploadForm();
if($request->isPost){
$model->file = UploadedFile::getInstance($model, ‘file‘);
if ($model->file && $model->validate()) {
$r = $model->file->saveAs(‘uploads/‘ . $model->file->baseName . ‘.‘. $model->file->extension);    //这是上传,uploads文件夹要自己手动创建
}
}else{
return $this->renderPartial(‘adv_add.html‘,[‘model‘ => $model]);
}
}

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

 

显示页面内容:

 

<?php
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin([‘options‘ => [‘enctype‘ => ‘multipart/form-data‘]]) ?>

<table class="table table-bordered table-hover definewidth m10">

 

 

<tr>
   <td class="tableleft">上传广告图</td>
   <td><?= $form->field($model, ‘file‘)->fileInput() ?></td>
</tr>

<tr>
   <td class="tableleft"></td>
   <td>
       <button type="submit" class="btn btn-primary" type="button">保存</button>
       <button type="button" class="btn btn-success" name="backid" id="backid">返回广告列表</button>
   </td>
</tr>

<?php ActiveForm::end() ?>

 

以上是关于yii2 文件上传的主要内容,如果未能解决你的问题,请参考以下文章

Yii2.0 多文件上传

Yii2的BlueImp文件上传小工具

yii2文件上传

yii2一次上传很多文件接口开发(yii自带的UploadedFile类+postman(多文件上传

在 Yii2 中通过 Ajax 上传不包括文件

yii2组件之多图上传插件FileInput的详细使用