We’re going to take a look at using FormData and Vue.js to upload files, such as images, to a remote web service. Either of the two web services that we’ve previously created, whether it be with Hapi or Express, will work for this example.

Creating a New Vue.js Web Application with the Vue CLI

To make this example simple and easy to understand, we’re going to start with a brand new project. Using the Vue CLI, execute the following command:

vue init webpack upload-project

When prompted, just say no to everything including the question regarding the router component. It doesn’t matter if we use a standalone build setup or runtime-only.

After the project is created, execute the following:

cd upload-project
npm install

The above commands will install all the dependencies required for the scaffolded Vue.js project.

With the HTML component for selecting files, we cannot directly bind a variable. For this reason, everything is going to be based on methods.

We will be sending FormData to our remote web service. When data is populated in our file explorer, we will be calling the fileChange method, passing the file data. This data will be added as FormData. When we finally choose to upload our data, the upload method will be called. The upload method will do a POST request with the axios library.

The <template> block that pairs in the src/App.vue file is quite simple. It looks like the following:

In the above HTML, we have several <input> components for files. If you think back to the Hapi with Node.js example, we are accepting multiple files in a single request. Each will trigger a change event and add the file information to our FormData.

When we want to upload, the button will trigger the upload method via the v-on:click event.

The complete code in our src/App.vue file for our project should look like the following:

If everything was done correctly in the Vue.js application and the backend application, you should see files on your server depending on what you’ve chosen to upload.

Conclusion

You just saw how to upload files to a remote web service via a Vue.js web application. By leveraging FormData and the change events, we can accomplish the job with minimal effort. In most applications that I build, there is an upload requirement, most typically for images, so this example works perfectly.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.