Yii2 Update User Profile Photo

By Er. Amit Thatey
0 Comments  

Uploading files in Yii is done via a form model, its validation rules and some controller code.


Step 1:

For upload a single file you would create a model class that will handle uploads file and use an attribute of the model to keep the uploaded file instance. Create models/user.php with the following content:


Created a user model with an attribute photo that will become <input type="file"> in the HTML form. The attribute has the validation rule named photo that uses yii validators.

Uploading files in Yii is usually done with the help of yii\web\UploadedFile which encapsulates each uploaded file as an UploadedFile object. If you need to make the file upload mandatory, use skipOnEmpty false and file upload not mandatory, use skipOnEmpty ture.


Step 2:

To render to View for the file upload form:


It is important to remember that you add the enctype option to the form so that the file can be properly uploaded. The fileInput() call will render a <input type="file"> tag which will allow users to select a file to upload. The 'enctype' => 'multipart/form-data' is necessary because it allows file uploads.


Step 3:

Create uploads direcoty on yii2basic/web for save the file upload.


Step 4:

Create a Controller that will handle file upload:



The yii\web\UploadedFile::getInstance() method is called to represent the uploaded file as an UploadedFile instance. with setting all these, now you will be able to upload file, save it in upload folder and save the file name in database table filed.


Comments