How to upload image using Vuejs?

How to upload image using Vuejs?

Handling files is always a task. In this article, we will talk about how to uploads image using VueJs. We will create an images uploader that allow user to upload single or multiple images file by drag and drop or select file dialog.

Handling files is always a task. In this article, we will talk about how to uploads image using VueJs. We will create an images uploader that allow user to upload single or multiple images file by drag and drop or select file dialog.

We will then upload the selected images and display them accordingly. We will also learn to filter the upload file type, for example, we only allow images, do not allow file type like PDF.

How to upload image using Vuejs

Table of Contents

  • File Upload UI & API
  • Setup Project with Vue-Cli
  • File Upload Component
  • Style our File Upload Component
  • File Upload Component Code
  • File Upload Service
  • Display Success and Failed Result
  • Fake the Upload in Front-end
  • Bonus: Delay Your Promises
  • Summary

Sourcecode: https://github.com/chybie/file-upload-vue

Demo: https://vue-file-upload-1126b.firebaseapp.com/

File Upload UI & API

File upload consists of two parts: the UI (front-end) and the API (back-end). We will be using VueJs to handle the UI part. We need a backend application to accept the uploaded files.

Setup Project with Vue-Cli

We will be using vue-cli to scaffold Vue.js projects. We will be using the webpack-simple project template.

# install cli
npm install vue-cli -g

# then create project, with sass
# follow the instructions to install all necessary dependencies
vue init webpack-simple file-upload-vue

Alright, all set. Let's proceed to create our component.

File Upload Component

We will write our code in App.vue. Remove all the auto-generated code in the file.









        # Upload images


          <input type="file" multiple :name="uploadFieldName" :disabled="isSaving" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length"
            accept="image/*" class="input-file">

              Drag your file(s) here to begin
 or click to browse


              Uploading {{ fileCount }} files...










Notes:-

  1. Our App.vue component consists of 3 part: template (HTML), script (Javascript) and styles (SASS).
  2. Our template has an upload form.
  3. The form attribute enctype="multipart/form-data" is important. To enable file upload, this attribute must be set. Learn more about enctype here.
  4. We have a file input `` to accept file upload. The property multiple indicate it's allow multiple file upload. Remove it for single file upload.
  5. We will handle the file input change event. Whenever the file input change (someone drop or select files), we will trigger the filesChange function and pass in the control name and selected files $event.target.files, and then upload to server.
  6. We limit the file input to accept images only with the attribute accept="image/*".
  7. The file input will be disabled during upload, so user can only drop / select files again after upload complete.
  8. We capture the fileCount of the when file changes. We use the fileCount variable in displaying number of files uploading Uploading {{ fileCount }} files....

Style our File Upload Component

Now, that's the interesting part. Currently, our component look like this:

upload image using Vuejs

We need to transform it to look like this:

upload image using Vuejs

Let's style it!


...


With only few lines of scss, our component looks prettier now.

Notes:-

  1. We make the file input invisible by applying opacity: 0 style. This doesn't hide the file input, it just make it invisible.
  2. Then, we style the file input parent element, the dropbox css class. We make it look like a drop file zone surround with dash.
  3. Then, we align the text inside dropbox to center.

File Upload Component Code

Let's proceed to code our component.


...


Notes:-

  1. Our component will have a few statuses: STATUS_INITIAL, STATUS_SAVING, STATUS_SUCCESS, STATUS_FAILED, the variable name is pretty expressive themselves.
  2. Later on, we will call the Hapi.js file upload API to upload images, the API accept a field call photos. That's our file input field name.
  3. We handle the file changes with the filesChange function. FileList is an object returned by the files property of the HTML element. It allow us to access the list of files selected with the element. Learn more here.
  4. We then create a new FormData, and append all our photos files to it. FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values. Learn more here.
  5. The save function will call our file upload service (hang on, we will create the service next!). We also set the status according to the result.
  6. mount() is the vue component life cycle hook. During that point, we will set our component status to initial state.

File Upload Service

Let's proceed to create our service. We will be using axios to make HTTP calls.

Install axios

# install axios
npm install axios --save

Service

// file-upload.service.js

import * as axios from 'axios';

const BASE_URL = 'http://localhost:3001';

function upload(formData) {
    const url = `${BASE_URL}/photos/upload`;
    return axios.post(url, formData)
        // get data
        .then(x => x.data)
        // add url field
        .then(x => x.map(img => Object.assign({},
            img, { url: `${BASE_URL}/images/${img.id}` })));
}

export { upload }

Nothing much, the code is pretty expressive itself. We upload the files, wait for the result, map it accordingly.

You may run the application now with npm run dev command. Try uploading a couple of images, and it's working! (Remember to start your backend server)

Display Success and Failed Result

We can upload the files successfully now. However, there's no indication in UI. Let's update our HTML template.







      ...form...



        ## Uploaded {{ uploadedFiles.length }} file(s) successfully.


          [Upload again](javascript:void(0) "Upload again")



            ![](item.url)





        ## Uploaded failed.


          [Try again](javascript:void(0) "Try again")

{{ uploadError }}





Notes:-

  1. Display the uploaded image when upload successfully.
  2. Display the error message when upload failed.

Fake the Upload in Front-end

If you are lazy to start the back-end application (Hapi, Express, etc) to handle file upload. Here is a fake service to replace the file upload service.

// file-upload.fake.service.js

function upload(formData) {
    const photos = formData.getAll('photos');
    const promises = photos.map((x) => getImage(x)
        .then(img => ({
            id: img,
            originalName: x.name,
            fileName: x.name,
            url: img
        })));
    return Promise.all(promises);
}

function getImage(file) {
    return new Promise((resolve, reject) => {
        const fReader = new FileReader();
        const img = document.createElement('img');

        fReader.onload = () => {
            img.src = fReader.result;
            resolve(getBase64Image(img));
        }

        fReader.readAsDataURL(file);
    })
}

function getBase64Image(img) {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;

    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);

    const dataURL = canvas.toDataURL('image/png');

    return dataURL;
}

export { upload }

Came across this solution in this Stackoverflow post. Pretty useful. My online demo is using this service.

Basically, what the code do is read the source, draw it in canvas, and save it as data url with the canvas toDataURL function. Learn more about canvas here.

Now you can swap the real service with the fake one.


...




...

Done! Stop your backend API, refresh your browser, you should see our app is still working, calling fake service instead.

Bonus: Delay Your Promises

Sometimes, you may want to delay the promises to see the state changes. In our case, the file upload may complete too fast. Let's write a helper function for that.

// utils.js

// utils to delay promise
function wait(ms) {
    return (x) => {
        return new Promise(resolve => setTimeout(() => resolve(x), ms));
    };
}

export { wait }

Then, you can use it in your component


...


Summary

That's it. This is how you can handle file upload without using any 3rd party libraries and plugins in Vue. It isn't that hard right?

The UI (Front-end)

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

What are the differences between the various JavaScript frameworks? E.g. Vue.js, Angular.js, React.js

What are the differences? Do they each have specific use contexts?

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

In this article we will discuss full details and comparison of both Ember.js and Vue.js