yii2文件上传 用yii自带表单 [ 2.0 版本 ]
1.创建Model类 UploadForm.php
<?php
namespace app\models;
use yii\base\Model;
class UploadForm extends Model
{
public $imageFile;
//制定规则
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
//上传
public function upload()
{
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
}
}
2.在web目录下创建uploads文件夹
3.创建控制器
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class IndexController extends Controller{
//上传方法
public function actionUpload()
{
//实例化上传model类
$model = new UploadForm();
if(Yii::$app->request->isPost){
//取出model中的图片信息
$model->imageFile = UploadedFile::getInstance($model,'imageFile');
if($model->upload()){
//上传成功添加入库
$img = $model->imageFile->name;
//添加入库
$res = Yii::$app->db->createCommand()->insert('photo',['img'=>$img])->execute();
//判断是否上传成功
if($res){
return $this->redirect(['list']);
}
return $this->goBack();
}
}
return $this->render('index', ['model' => $model]);
}
}
4.视图
<?php
use yii\widgets\ActiveForm;
?>
<h2>上传图片</h2>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput(['class'=>'btn'])->label("上传") ?>
<button class="btn">上传</button>
<?php ActiveForm::end() ?>
啦啦啦啦一朵花 北京
注册时间:2017-09-21
最后登录:2018-12-25
在线时长:3小时45分
最后登录:2018-12-25
在线时长:3小时45分
- 粉丝2
- 金钱55
- 威望10
- 积分185
共 1 条评论
可以提供数据表结构? 多谢啦