In this tutorial, I will show you way to build a Vue Upload Image with Preview example that uses Axios and Multipart File for making HTTP request to server. You will also know how to add Bootstrap progress bar, show response message and display list of images’ information (with url).
More Practice:
– Vue Multiple Files Upload with Axios, FormData and Progress Bars
– Vue.js CRUD Application with Vue Router & Axios
– Vue.js JWT Authentication with Vuex and Vue Router
– Vue Pagination with Axios and API example
Using Vuetify: Vuetify Image Upload with Preview example
Contents
- Overview
- Technology
- Setup Vue Upload Image with Axios Project
- Structure the Project
- Add Bootstrap to the project
- Initialize Axios for Vue HTTP Client
- Create Service for Upload Images
- Create Component for Upload Images
- Add Upload Image Component to App Component
- Configure Port for Vue Image Upload App
- Run the App
- Further Reading
- Conclusion
- Source code
Overview
We’re gonna create a Vue Image upload with Preview using Axios 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
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
Or: Spring Boot Multipart File upload (to database) example
Technology
- Vue 2.6
- Axios 0.21.1
- Bootstrap 4
Setup Vue Upload Image with Axios Project
Open cmd at the folder you want to save Project folder, run command:
vue create vue-upload-image-axios
You will see some options, choose default (babel, eslint).
Then we add Axios library with command: npm install axios
.
Structure the Project
After the process is done. We create new folders and files like this:
– UploadFilesService provides methods to save File and get Files using Axios.
– UploadImage component contains upload image form, progress bar, display of list images.
– App.vue is the container that we embed all Vue components.
– index.html for importing the Bootstrap.
– http-common.js initializes Axios with HTTP base Url and headers.
– We configure port for our App in vue.config.js
Add Bootstrap to the project
Open index.html and add following line into <head>
tag:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link type="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
</head>
...
</html>
Initialize Axios for Vue HTTP Client
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 Upload Images
This service will use Axios to send HTTP requests.
There are 2 functions:
upload(file)
: POST form data with a callback for tracking upload progressgetFiles()
: GET list of Files’ 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 Progress Bar, Card, Button and Message.
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: [],
};
},
};
Next we define selectImage()
method which helps us to get the selected Image from ref="file"
element in HTML template later.
export default {
name: "upload-image",
...
methods: {
selectImage() {
this.currentImage = this.$refs.file.files.item(0);
this.previewImage = URL.createObjectURL(this.currentImage);
this.progress = 0;
this.message = "";
},
}
};
We access current File as the first Item. 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.
Next we define upload()
method for upload image:
export default {
name: "upload-image",
...
methods: {
...
upload() {
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;
});
},
}
};
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
variable.
Here, imageInfos
is an array of {name, url}
objects.
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. Add the following content to <template>
:
<template>
<div>
<div class="row">
<div class="col-8">
<label class="btn btn-default p-0">
<input
type="file"
accept="image/*"
ref="file"
@change="selectImage"
/>
</label>
</div>
<div class="col-4">
<button
class="btn btn-success btn-sm float-right"
:disabled="!currentImage"
@click="upload"
>
Upload
</button>
</div>
</div>
<div v-if="currentImage" class="progress">
<div
class="progress-bar progress-bar-info"
role="progressbar"
:aria-valuenow="progress"
aria-valuemin="0"
aria-valuemax="100"
:style="{ width: progress + '%' }"
>
{{ progress }}%
</div>
</div>
<div v-if="previewImage">
<div>
<img class="preview my-3" :src="previewImage" alt="" />
</div>
</div>
<div v-if="message" class="alert alert-secondary" role="alert">
{{ message }}
</div>
<div class="card mt-3">
<div class="card-header">List of Images</div>
<ul class="list-group list-group-flush">
<li
class="list-group-item"
v-for="(image, index) in imageInfos"
:key="index"
>
<a :href="image.url">{{ image.name }}</a>
</li>
</ul>
</div>
</div>
</template>
In the code above, we use Bootstrap Progress Bar:
.progress
as a wrapper- inner
.progress-bar
to indicate the progress .progress-bar
requiresstyle
to set the width by percentage.progress-bar
also requiresrole
and some aria attributes to make it accessible- Labels to progress bar is the text within it
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>
<div id="app">
<div class="container" style="width:600px">
<div class="my-4">
<h3>bezkoder.com</h3>
<h4>Vue.js upload Image with Preview</h4>
</div>
<upload-image></upload-image>
</div>
</div>
</template>
<script>
import UploadImage from "./components/UploadImage";
export default {
name: "App",
components: {
UploadImage
}
};
</script>
Configure Port for Vue 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.
In src
folder, create vue.config.js file with following content:
module.exports = {
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
Then run this Vue Image Upload App with command: npm run serve
.
Open Browser with url http://localhost:8081/
and check the result.
Further Reading
Fullstack CRUD App:
- Vue.js + Node.js + Express + MySQL
- Vue.js + Node.js + Express + PostgreSQL
- Vue.js + Node.js + Express + MongoDB
- Vue.js + Spring Boot + Embedded Database (H2)
- Vue.js + Spring Boot + MySQL
- Vue.js + Spring Boot + PostgreSQL
- Vue.js + Spring Boot + MongoDB
- Vue.js + Django Rest Framework
Conclusion
Today we’re learned how to build an example for upload Image with Preview using Vue and Axios. We also provide the ability to show list of images, upload progress with Bootstrap, and to download image 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
Or: Spring Boot Multipart File upload (to database) example
If you want to upload multiple files like this:
Please visit:
Vue Multiple Files Upload with Axios, FormData and Progress Bars
Or use Vuetify with the tutorial:
Vuetify Image Upload with Preview example
Source code
The source code for this Vue Client is uploaded to Github.
Hello ,
Thank you so much for this tuto. (and all of the others).
Really BIG Good job !!
Just a question, I’m trying to use it with my dev in Vue3 (with TS) and with API composition.
So I convert the code but I’ve a doubt and my tries doen t work, about the ” this.$refs.file …..” do you know what is good “translation code” ?? please
Thank you , have a good day