VueJS Image Upload

VueJS Image Upload

In this tutorial we’ll create a VueJS image upload component so that users can upload an image to use as an avatar in the application. The goal is to re create the mechanism of an image upload via an html form, however it will all be done in a Vue component. This will allow for real time image updating in the browser, in addition to putting the image in storage and setting the avatar image path in the database in one fell swoop. There is a lot to cover, so let’s jump right in to uploading an image to the server using VueJS.

Getting The Database Ready

When uploading an image, you typically store the image on some type of storage medium such as the local filesystems, Amazon S3, or maybe even Rackspace Cloud Storage. With regard to the database, it is the path to the image that you usually store there. In other words, a string representation of how to reach the image. For our purposes, we’ll add a column to the users table named avatar_path. To do this, we’ll create and run this migration.

vagrant@homestead:~/Code/forumio$ php artisan make:migration add_avatar_path_to_users_table --table=users

vagrant@homestead:~/Code/forumio$ php artisan migrate
Migrating: 2018_02_27_193627_add_avatar_path_to_users_table
Migrated:  2018_02_27_193627_add_avatar_path_to_users_table

Migrations are flexible in this way. We are able to set up a migration file to simply add a column without the need to rollback existing schema and data in the database. If we look at the users table, here we see what we need. A new column where we can store the image file path which begins with a null value.

A User Can Upload An Avatar Test

Now what we’ll do is create a test class of AddAvatarTest and the first test method will be test_a_user_may_add_an_avatar_to_their_profile().

  • Given we have a signed in user
  • Given we have a disk to store to (faked)
  • When we submit a json post request to the api
  • Then the file path should match the users avatar_path
  • Then the disk should contain that file path

Now we can start hammering out the test to see what we need to do in order for it to pass.

vagrant@homestead:~/Code/forumio$ phpunit --filter test_a_user_may_add_an_avatar_to_their_profile
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 1.36 seconds, Memory: 10.00MB

There was 1 error:

1) Tests\Feature\AddAvatarTest::test_a_user_may_add_an_avatar_to_their_profile
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: POST http://localhost/api/users/1/avatar

The NotFoundHttpException means we are missing a route. Ok, we can add a new route to support the file upload to our web.php routes file. Add this to the end of that file. It is a post request to the api namespace which has a user wildcard referencing a UserAvatarController class with a method of store() which has an auth middleware and a named route of ‘avatar’. LOL! Sorry, run on sentence.

The first error is fixed, let’s run the test to see what is next.

vagrant@homestead:~/Code/forumio$ phpunit --filter test_a_user_may_add_an_avatar_to_their_profile
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 1.23 seconds, Memory: 10.00MB

There was 1 error:

1) Tests\Feature\AddAvatarTest::test_a_user_may_add_an_avatar_to_their_profile
ReflectionException: Class App\Http\Controllers\Api\UserAvatarController does not exist

That sounds about right. We have a ReflectionException which states the UserAvatarController class does not exist. Let’s create it!

vagrant@homestead:~/Code/forumio$ php artisan make:controller Api/UserAvatarController
Controller created successfully.

That should fix error number 2, let’s see what is next.

vagrant@homestead:~/Code/forumio$ phpunit --filter test_a_user_may_add_an_avatar_to_their_profile
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 894 ms, Memory: 10.00MB

There was 1 error:

1) Tests\Feature\AddAvatarTest::test_a_user_may_add_an_avatar_to_their_profile
BadMethodCallException: Method [store] does not exist on [App\Http\Controllers\Api\UserAvatarController].

Now we see that we are missing the store() method in that controller. We are letting the test results guide us on each next step. We can add that method now. The store method is going to need to actually perform some work as well. So let’s think about what we want it to do. Well first off, we should validate that the user has provided an image in the request. Next, we are going to make use of a policy which we will create in a moment to determine if the user has the permissions to upload this image. Last, we’ll set the avatar_path to be stored in the avatars public directory. So let’s add this code like so.

Let’s run the test and see what happens.

vagrant@homestead:~/Code/forumio$ phpunit --filter test_a_user_may_add_an_avatar_to_their_profile
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 1.44 seconds, Memory: 10.00MB

There was 1 failure:

1) Tests\Feature\AddAvatarTest::test_a_user_may_add_an_avatar_to_their_profile
Failed asserting that null matches expected 'http://localhost/avatars/ntyWkGe7Xvph8dxNZXPQe8HgEELzgZHW3G4B5BFe.jpeg'.


Tests: 1, Assertions: 1, Failures: 1.

Well this is interesting. It appears that the file itself is in fact being stored, but the path on the user object is null. Ok, we probably need to allow that column to be filled. Mass exception handling is likely protecting that right now. So in the User.php model we can add.

Ok, we’re looking good now!
test_a_user_may_add_an_avatar_to_their_profile is now passing

Create A User Policy

We’ll make use of a policy object to set permissions for users to update their avatar. Of course we don’t want someone to be able to update a different user’s avatar image, so having a User policy will make sure this base is covered.

vagrant@homestead:~/Code/forumio$ php artisan make:policy UserPolicy
Policy created successfully.

The rule here is simply that the id of the signed in user matches that of the user being updated. If they match, then it’s the same person and we are good to go.

Anytime you make a new policy, you’ll need to register it in AuthServiceProvider for it to actually take effect.

Now with a User policy, we’ll be able to selectively show an upload area only for the users that have permissions to see it. Now, before we get to far ahead, let’s add just a couple of more tests to the AddAvatarTest class. This will ensure that only members can upload an avatar image, and that a valid image must be provided.

This test suite is passing, so we’re good.
AddAvatarTest suite passing

Linking Storage Directory To Public Directory

Before we start building out the front end, we know that we are going to need to have access to the images in the public directory. But wait, Laravel stores images in the storage directory. So what do we do? We set up a symlink!

Here is what it does:

vagrant@homestead:~/Code/forumio$ php artisan help storage:link
  Create a symbolic link from "public/storage" to "storage/app/public"

Now we can run it.

vagrant@homestead:~/Code/forumio$ php artisan storage:link

In Filesystem.php line 228:

  symlink(): Operation not supported

Whoops! No worries, this is due to Windows being the host OS in my case. Just like in this form submission tutorial, we’ll have to manually make the symlink on the host OS.

C:\>mklink /D C:\localdev\forumio\public\storage C:\localdev\forumio\storage\app\public
symbolic link created for C:\localdev\forumio\public\storage <<===>> C:\localdev\forumio\storage\app\public

Setting A Default Avatar

When a user first signs up for an account, they might not feel like uploading an image avatar. In that case, we should provide a default image so that the layout looks consistent. We can add this function to the User.php model. It gets the users image avatar, and if that is not present it will use the default.

The VueJs Image Uploader

Now we can start tackling the front end side and build out the component to upload an image as an avatar. Actually, we’ll do this in two steps. First we’ll create the ImageUpload.vue component.
vuejs ImageUpload component
The component will have the following markup.

The second portion of the Vue image uploader will be the AvatarForm.vue component.
vuejs avatar form component

Register The Vue Component

We can register the AvatarForm.vue component using the highlighted line below in app.js.

Set A Default Image

In order to reference a default image, we need to store one on the server. We can place a default.png file in public/images/avatars like this.
default avatar image

Displaying An Avatar

In the threads/show.blade.php file we can now reference the avatar as seen here.

Looking pretty good!
avatar now shows in the view file

Adding The Image Uploader To Profiles Page

Finally, we’ll go into the profiles/show.blade.php view file and add in the <avatar-form> Vue component. This should allow us to easily select an image and have it persist to the server while updating the avatar image instantly in the user interface.

We now log in as Tom, and visit his profile page. We can click the choose file button, and watch the image avatar update in real time. The cool thing is that not only did it update in real time in the browser, the image was also stored in storage in addition to the file path getting stored in the database. This means when the page is reloaded, the image will persist.
vue js image upload example

How The VueJs Image Upload Component Works

We didn’t talk a lot about how the code works inside the Vue Components so let’s review how this works.

The user chooses an image which causes the change event to fire. This results in the onChange function getting called.

Inside the onChange method, we first check to see if a file has been provided. If not, we just return.

If a file was selected, we will place it into the file variable

Then the Javascript File Reader Object is used to read the contents of the file provided. Specifically, the readAsDataURL() method is used to determine the image representation of the file in a base64 encoded string. This is then set as the image source, which is what allows the image to update instantly in the browser.

At this point a loaded event is fired which AvatarForm.vue will listen for.

Now, in AvatarForm.vue, the loaded event is picked up on and fires the onLoad method.

The onLoad method sets the avatar source for real time image updating, then stores the file path in the database.

The persist method makes use of the Javascript FormData interface to create a set of key/value pairs representing the form fields and their values, which are then sent as a post request to the server endpoint we had setup using axios.

VueJS Image Upload Summary

That pretty much sums up how the lifecycle of an avatar image upload works in VueJs. This tutorial had us creating the back end api in Laravel to support storing an image on the server, as well as using VueJs in concert with the Javascript FileReader and FormData objects to make a slick image upload component which renders in real time while also persisting to the database.