Vuetify Image Upload with Preview example

In this tutorial, I will show you way to use Vuetify to build Image Upload with Preview example using Axios and Multipart File for making HTTP requests. You will also know how to add progress bar, show response message and display list of images’ information (with url).

More Practice:
Vuetify Multiple Images Upload example
Vuetify data-table example with a CRUD App | v-data-table
Vue.js JWT Authentication with Vuex and Vue Router

Using Bootstrap: Vue File Upload example with Axios & Bootstrap


Overview

We’re gonna create a Vuetify Image upload with Preview application in that user can:

  • see the upload process (percentage)
  • view all uploaded images
  • link to the file when clicking on the image’s name

vuetify-image-upload-preview-example

Here are APIs that we will use Axios to make HTTP requests:

Methods Urls Actions
POST /upload upload a File
GET /files get List of Files (name & url)
GET /files/[filename] download a File

You can find how to implement the Rest APIs Server at one of following posts:
Node.js Express File Upload Rest API example
Node.js Express File Upload to MongoDB example
Node.js Express File Upload to Google Cloud Storage example
Spring Boot Multipart File upload (to static folder) example
Spring Boot Upload File to Database example

Technology

  • Vue 2.6
  • Axios 0.21.1
  • Vuetify 2

Setup Vuetify Image Upload Project

Open cmd at the folder you want to save Project folder, run command:
vue create vuetify-image-upload-preview

You will see some options, choose default (babel, eslint).

After the Vue project is created successfully, we import Vuetify with command: vue add vuetify.
The Console will show:

�📦  Installing vue-cli-plugin-vuetify...

+ [email protected]
added 5 packages from 7 contributors and audited 1277 packages in 25.013s
found 0 vulnerabilities

✔  Successfully installed plugin: vue-cli-plugin-vuetify

? Choose a preset: Default (recommended)

�🚀  Invoking generator for vue-cli-plugin-vuetify...
�📦  Installing additional dependencies...

added 7 packages from 5 contributors and audited 1284 packages in 41.183s
found 0 vulnerabilities

⚓  Running completion hooks...

✔  Successfully invoked generator for plugin: vue-cli-plugin-vuetify
   The following files have been updated / added:

     src/assets/logo.svg
     src/plugins/vuetify.js
     vue.config.js
     package-lock.json
     package.json
     public/index.html
     src/App.vue
     src/components/HelloWorld.vue
     src/main.js

Open plugins/vuetify.js, you can see:

import Vue from 'vue';
import Vuetify from 'vuetify/lib';

Vue.use(Vuetify);

export default new Vuetify({
});

Then in main.js file, Vuetify object will added automatically to Vue App:

import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';

Vue.config.productionTip = false

new Vue({
  vuetify,
  render: h => h(App)
}).$mount('#app')

And vue.config.js:

module.exports = {
  transpileDependencies: ["vuetify"]
};

Project Structure

Let’s remove unnecessary folders and files, then create new ones like this:

vuetify-image-upload-preview-example-project-structure

Let me explain it briefly.

plugins/vuetify.js imports Vuetify library, initializes and exports Vuetify object for main.js.
We don’t need to do anything with these 2 files because the command add Vuetify helped us.

UploadFilesService provides methods to save File and get Files using Axios.
UploadImage component contains image upload form, progress bar, list of images display.
App.vue is the container that we embed all Vue components.

http-common.js initializes Axios with HTTP base Url and headers.
– We configure transpile Dependencies and port for our App in vue.config.js

Initialize Axios for Vuetify Image Upload HTTP Client

Now we add Axios library with command: npm install axios.

Under src folder, we create http-common.js file like this:

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080",
  headers: {
    "Content-type": "application/json"
  }
});

Remember to change the baseURL, it depends on REST APIs url that your Server configures.

Create Service for Image Upload

This service will use Axios to send HTTP requests.
There are 2 functions:

  • upload(file): POST form data with a callback for tracking upload progress
  • getFiles(): GET list of Images’ information

services/UploadFilesService.js

import http from "../http-common";

class UploadFilesService {
  upload(file, onUploadProgress) {
    let formData = new FormData();

    formData.append("file", file);

    return http.post("/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      },
      onUploadProgress
    });
  }

  getFiles() {
    return http.get("/files");
  }
}

export default new UploadFilesService();

– First we import Axios as http from http-common.js.

FormData is a data structure that can be used to store key-value pairs. We use it to build an object which corresponds to an HTML form with append() method.

– We pass onUploadProgress to exposes progress events. This progress event are expensive (change detection for each event), so you should only use when you want to monitor it.

– We call the post() & get() method of Axios to send an HTTP POST & Get request to the File Upload server.

Create Component for Upload Images

Let’s create a Image Upload UI with Vuetify Progress Bar, Button and Alert. We also have Card and List Item Group for displaying uploaded files.

First we create a Vue component template and import UploadFilesService:

components/UploadImage.vue

<template>

</template>

<script>
import UploadService from "../services/UploadFilesService";

export default {
  name: "upload-image",
  data() {
    return {

    };
  },
  methods: {
  
  }
};
</script>

Then we define the some variables inside data()

export default {
  name: "upload-image",
  data() {
    return {
      currentImage: undefined,
      previewImage: undefined,

      progress: 0,
      message: "",

      imageInfos: []
    };
  },
};
  • imageInfos is an array of {name, url} objects. We’re gonna display its data in a Vuetify v-list and v-list-item-group.
  • progress is the percentage of image upload progress.

Next we define selectImage() method which helps us to get the selected Image from v-file-input element in HTML template later.

export default {
  name: "upload-image",
  ...
  methods: {
    selectImage(image) {
      this.currentImage = image;
      this.previewImage = URL.createObjectURL(this.currentImage);
      this.progress = 0;
      this.message = "";
    },
  }
};

We access currentImage as the input parameter image. Then we call UploadService.upload() method on the currentImage with a callback.

We also use URL.createObjectURL() static method to get the image preview URL as previewImage. This method produces a DOMString including a URL describing the object provided in the parameter. The URL life is tied to the document in the window on which it was created.

We also define upload() method as following:

export default {
  name: "upload-image",
  ...
  methods: {
    ...
    upload() {
      if (!this.currentImage) {
        this.message = "Please select an Image!";
        return;
      }

      this.progress = 0;

      UploadService.upload(this.currentImage, (event) => {
        this.progress = Math.round((100 * event.loaded) / event.total);
      })
        .then((response) => {
          this.message = response.data.message;
          return UploadService.getFiles();
        })
        .then((images) => {
          this.imageInfos = images.data;
        })
        .catch((err) => {
          this.progress = 0;
          this.message = "Could not upload the image! " + err;
          this.currentImage = undefined;
        });
    },
  },
};

We check if the currentImage is here or not. Then we call UploadService.upload() method on the currentImage with a callback.

The progress will be calculated basing on event.loaded and event.total.
If the transmission is done, we call UploadService.getFiles() to get the images’ information and assign the result to imageInfos array.

We also need to do this work in mounted() method:

export default {
  name: "upload-image",
  ...
  mounted() {
    UploadService.getFiles().then(response => {
      this.imageInfos = response.data;
    });
  }
};

Now we implement the HTML template of the Upload Image UI using Vuetify. Add the following content to <template>:

<template>
  <div>
    <v-row no-gutters justify="center" align="center">
      <v-col cols="8">
        <v-file-input
          show-size
          label="Select Image"
          accept="image/*"
          @change="selectImage"
        ></v-file-input>
      </v-col>

      <v-col cols="4" class="pl-2">
        <v-btn color="success" dark small @click="upload">
          Upload
          <v-icon right dark>mdi-cloud-upload</v-icon>
        </v-btn>
      </v-col>
    </v-row>

    <div v-if="progress">
      <div>
        <v-progress-linear
          v-model="progress"
          color="light-blue"
          height="25"
          reactive
        >
          <strong>{{ progress }} %</strong>
        </v-progress-linear>
      </div>
    </div>

    <div v-if="previewImage">
      <div>
        <img class="preview my-3" :src="previewImage" alt="" />
      </div>
    </div>

    <v-alert v-if="message" border="left" color="blue-grey" dark>
      {{ message }}
    </v-alert>

    <v-card v-if="imageInfos.length > 0" class="mx-auto">
      <v-list>
        <v-subheader>List of Images</v-subheader>
        <v-list-item-group color="primary">
          <v-list-item v-for="(image, index) in imageInfos" :key="index">
            <a :href="image.url">{{ image.name }}</a>
          </v-list-item>
        </v-list-item-group>
      </v-list>
    </v-card>
  </div>
</template>

In the code above, we use Vuetify Progress linear: v-progress-linear. This component will be responsive to user input with v-model. We bind the progress model (percentage) to display inside of the progress bar.

The v-btn button will call upload() method, then notification is shown with v-alert.

The preview of uploading image is shown: <img class="preview" src={previewImage} />

Add Upload Image Component to App Component

Open App.vue and embed the UploadImage Component with <upload-image> tag.

<template>
  <v-app>
    <v-container fluid style="width: 600px">
      <div class="mb-5">
        <h1>bezkoder.com</h1>
        <h2>Vuetify Image Upload with Preview</h2>
      </div>

      <upload-image></upload-image>
    </v-container>
  </v-app>
</template>

<script>
import UploadImage from "./components/UploadImage";

export default {
  name: "App",
  components: {
    UploadImage,
  },
};
</script>

Configure Port for Vuetify Image Upload App

Because most of HTTP Server use CORS configuration that accepts resource sharing restricted to some sites or ports. So you need to configure port for our App.

Modify vue.config.js file by adding devServer:

module.exports = {
  transpileDependencies: ["vuetify"],
  devServer: {
    port: 8081,
  },
};

We’ve set our app running at port 8081. vue.config.js will be automatically loaded by @vue/cli-service.

Run the App

First you need to run one of following Rest APIs Server:
Node.js Express File Upload Rest API example
Node.js Express File Upload to MongoDB example
Node.js Express File Upload to Google Cloud Storage example
Spring Boot Multipart File upload (to static folder) example
Spring Boot Multipart File upload (to database) example

Run this Vue Image Upload with Preview App using command:
npm run serve.

Open Browser with url http://localhost:8081/ and check the result.

Further Reading

If you want to build Vuetify CRUD App like this:

vuetify-data-table-example-crud-app-retrieve-all

You can visit the tutorial:
Vuetify data-table example with a CRUD App | v-data-table

Conclusion

Today we’re learned how to build an Vue/Vuetify example for Image Upload with Preview using Axios. We also provide the ability to show list of images, upload progress bar, and list of uploaded images from the server.

You can find how to implement the Rest APIs Server at one of following posts:
Node.js Express File Upload Rest API example
Node.js Express File Upload to MongoDB example
Node.js Express File Upload to Google Cloud Storage example
Spring Boot Multipart File upload (to static folder) example
Spring Boot Multipart File upload (to database) example

If you want to upload multiple images at once:

vuetify-multiple-image-upload-example

Please visit: Vuetify Multiple Images Upload example

Source Code

The source code for the Vue/Vuetify Client is uploaded to Github.