本人搜索了很多关于yii2利用自带UploadedFile实现上传图片介绍,下面我来记录一下。
创建一个 models/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'],];
}
}
视图文件
PHP;">
<?php $form = ActiveForm::begin([‘options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model,‘file')->fileInput() ?>
<?php ActiveForm::end() ?>
控制器
public function actionUpload()
{
$model = new UploadForm();
{
$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]);
}