How to Program With Yii2: Uploading Files

Final product image
What You'll Be Creating

If you're asking, "What's Yii?" check out my earlier tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released in October 2014.

In this How to Program With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. In this tutorial, I'll guide you through the basics of uploading files and images in Yii2. 

For these examples, we'll continue to imagine we're building a framework for posting simple status updates, e.g. our own mini-Twitter. The image above demonstrates writing a short update while uploading a picture I took of the Taj Mahal.

Just a reminder, I do participate in the comment threads below. I'm especially interested if you have different approaches, additional ideas or want to suggest topics for future tutorials. If you have a question or topic suggestion, please post below. You can also reach me on Twitter @reifman directly.

File Upload Plugins

Yii2 Image Uploads - Kartik File Input Widget Demo Examples

There are two file upload plugins for Yii2 that seem the most robust:

  1. The FileInput Widget by Kartik Visweswaran (shown above)
  2. The 2Amigos BlueImp File Uploader (a wrapper for the BlueImp JQuery File Uploader

For this tutorial, I decided to continue with Kartik's plugin. I found it easier to use and better documented than the 2Amigos plugin. However, the BlueImp File Uploader has some intriguing user experience features that you may want to explore (shown below):

Yii2 Image Uploads - 2Amigos and BlueImp File Upload Examples

Working With the FileInput Plugin

Let's begin to install and make use of the file uploader and integrate it into our Twitter-like status creation applet. Again, we'll use the Yii2 Hello application tree which you can download with the GitHub button link beside or below.

Installing the Plugin

First, we can use composer to add kartik-v/yii2-widget-fileinput to our application:

Expanding the Status Table

Next, we need to add fields for the file we're going to upload to our Status table. In this example, we'll let the user upload an image to go along with their status update.

The fields we'll add are for the uploaded files' original filename as well as a unique filename which will be stored on our server for display:

  • image_src_filename
  • image_web_filename

Create a new migration for adding these fields to the Status table:

Here's the customized migration to add the two fields as strings:

Then, run the migration:

Since Yii2 is built with a Model View Controller (MVC) architecture, there are three other coding areas which we need to implement for the file uploader:

  1. The Status Model
  2. The Status View and Form
  3. The Status Controller

Enhancing the Model Functionality

Now, we'll make changes to the /models/Status.php file. Primarily, we need to provide attributes and validation rules for the new image fields as well as the temporary $image variable the widget will use to upload the file.

Below, we add comments for the two new $image_xxx_filename variables and create a public temporary variable called $image:

Next, we'll add validation rules for our image such as file type and maximum size:

And new attribute labels for views:

Now we can move on to the View changes within the ActiveModel Form.

Adding Our View and Form Functionality

Integrating Image Upload to the Status Creation Form

Yii2 Image Uploads - Creating a Status with Our New File Input Capability

To enable the form integration of image uploading to Status updates (shown above), we need to make changes to the /views/status/_form.php file. 

First, we include the kartik\file\FileInput widget near the top and update the form to become multipart, which supports posting files:

Then, between the Permissions field and Submit buttons, we add the FileInput widget:

In the pluginOptions line, we restrict file types to common image formats such as jpg.

When complete, it will look something like this, waiting for the user to add an image:

Yii2 Image Uploads - Create Status Page with File Upload Added

Displaying the Image

I'm also going to add code to display the uploaded image for later (after we finish the controller support). 

First, I'll add it to the Status view page (/views/status/view.php), which is very basic. However, I'll display the image below the item details:

It will look something like this:

Yii2 Image Uploads - Enhanced Status View with Image Below

We'll also add a small thumbnail view to our Status index page (/views/status/index.php). I've added a custom column attribute to Yii2's GridView widget:

Ultimately, it will look like this:

Yii2 Image Uploads - Enhanced Status Index with Uploaded Image Thumbnails

Building the Controller Support

To make all of the above possible, we need to finish the controller integration. 

At the top of /controllers/StatusController.php, we have to include yii\web\UploadedFile:

Then we have to update the actionCreate function:

Essentially, this performs the following operations:

  1. We capture the original filename from the uploaded file's form information (image_src_filename).
  2. We generate a unique filename for our server (image_web_filename).
  3. We save the file to our upload directory (/web/uploads/status/).
  4. We save the model.
  5. We redirect to the enhanced view page.

You can see the final results with the image above, which includes a picture of the Taj Mahal.

Kartik's File Input Widget also offers more advanced configurations which he documents fairly well, such as Drag and Drop:

Yii2 Image Uploads - Enhanced File Input Widget Options with Drag and Drop

Check more of these out on the following pages:

What's Next?

I hope this helps you with the basics of file uploading in your Yii2 application. If you'd like to see another similar walk-through of this kind of functionality, check out Building Your Startup With PHP: User Settings, Profile Images and Contact Details. That tutorial offers a slightly different integration than this tutorial, using tabs, updating user profiles and scaling the images.

Yii2 File Uploader Meeting Planner User Profile Image Upload

Watch for upcoming tutorials in my How to Program With Yii2 series as I continue diving into different aspects of the framework. You may also want to check out my Building Your Startup With PHP series, which is using Yii2's advanced template as I build a real-world application.

If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page. My instructor page will include all the articles from this series as soon as they are published. 

Related Links

Here are a variety of links that I used to research and write this tutorial:

Tags:

Comments

Related Articles