yii2利用自带UploadedFile实现上传图片的示例

时间:2022-09-24 20:06:22

本人搜索了很多关于yii2利用自带UploadedFile实现上传图片介绍,下面我来记录一下。

创建一个 models/UploadForm.php:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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'],
  ];
 }
}

视图文件

?
1
2
3
4
5
6
7
8
9
10
11
<?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() ?>

控制器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use app\models\UploadForm;
use yii\web\UploadedFile;
 
 
 
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]);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.yiichina.com/code/448