Input file upload Yii2
Steps:
1. Create a action fileUpload
2. Create a model FileUploadForm
3. Create a form
FileUploadForm model:
namespace backend\models; use yii\base\Model; use yii\web\UploadedFile; class FileUploadForm extends Model { public $Files; public function rules() { return [ [['Files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg', 'maxFiles' => 2], ]; } public function uploadHere() { if ($this->validate()) { foreach ($this->Files as $file) { $file->saveAs('path/to/uploads/' . $file->baseName . '.' . $file->extension); } return true; } else { return false; } } }
Action FileUpload:
public function actionFileUpload() { $model = new FileUploadForm(); if (Yii::$app->request->isPost) { $model->Files = UploadedFile::getInstances($model, 'Files'); if ($model->uploadHere()) { // your code here return; } } return $this->render('file-upload', ['model' => $model]); }
File input form:
use yii\widgets\ActiveForm; $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) $form->field($model, 'Files[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ActiveForm::end()
ReplyDeleteIt is nice post and I found some interesting information on this blog, keep it up. Thanks for sharing. Offshore PHP Development in India