English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

yii2Example of Uploading Images with the Built-in UploadedFile

I have searched a lot about yii2Using the built-in UploadedFile to implement image upload introduction, I will record it below.

Create a 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 [
   
  ]
 }
}

View file

<?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() ?>

Controller

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

That's all for this article. Hope it will be helpful to everyone's learning, and also hope everyone will support the呐喊 tutorial more.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not edit manually, and does not bear relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like