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

创建一个 models/UploadForm.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'],
  ];
 }
}

视图文件

<"htmlcode">
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]);
}

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

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com