Yii2使用自带的UploadedFile实现的文件上传
我们先来看看在yii2中支持的图片上传怎么进行处理的。
首先我们创建model\Upload.php文件
<?php namespace backend\models; use Yii; use yii\web\UploadedFile; class Upload extends \yii\db\ActiveRecord { /** * @var UploadedFile|Null file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [["file"], "file",], ]; } }
下面我们看看view层是怎么渲染的
<?php use yii\widgets\ActiveForm; $form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?> <?= $form->field($model, "file")->fileInput() ?> <button>Submit</button> <?php ActiveForm::end(); ?>
最后实现controller层的实现
namespace backend\controllers; use backend\models\Upload; use yii\web\UploadedFile; class ToolsController extends \yii\web\Controller { /** * 文件上传 * 我们这里上传成功后把图片的地址进行返回 */ public function actionUpload () { $model = new Upload(); $uploadSuccessPath = ""; if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, "file"); //文件上传存放的目录 $dir = "../../public/uploads/".date("Ymd"); if (!is_dir($dir)) mkdir($dir); if ($model->validate()) { //文件名 $fileName = date("HiiHsHis").$model->file->baseName . "." . $model->file->extension; $dir = $dir."/". $fileName; $model->file->saveAs($dir); $uploadSuccessPath = "/uploads/".date("Ymd")."/".$fileName; } } return $this->render("upload", [ "model" => $model, "uploadSuccessPath" => $uploadSuccessPath, ]); } }
相关推荐
WasteLand 2020-10-18
Allinputs 2020-08-30
Ashes 2020-06-14
caiyiii 2020-06-14
kxguan 2020-06-14
daillo 2020-06-14
一粒沙里的世界 2020-06-14
ruxingli 2020-06-14
csssy00 2020-06-14
阿佐 2020-06-14
NameWFY 2020-05-28
NameWFY 2020-05-26
Robin罗兵 2020-05-16
caiyiii 2020-04-29
wmsjlihuan 2020-04-26
cbao 2020-04-26
csssy00 2020-04-19
igogo00 2020-03-09