In this tutorial, I will show you way to build a Vue File Upload example that uses Axios and Multipart File for making HTTP requests. You will also know how to add Bootstrap progress bar, show response message and display list of files’ information (with url).
More Practice:
– Vue upload Image using Axios (with Preview)
– Vue Multiple Files Upload with Axios, FormData and Progress Bars
– Vue.js 2 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 File Upload example
Contents
- Overview
- Technology
- Setup Vue File Upload Project
- Structure the Project
- Add Bootstrap to the project
- Initialize Axios for Vue HTTP Client
- Create Service for Upload Files
- Create Component for Upload Files
- Add Upload File Component to App Component
- Configure Port for Vue File Upload App
- Run the App
- Further Reading
- Conclusion
- Source code
Overview
We’re gonna create a Vue File upload application in that user can:
- see the upload process (percentage)
- view all uploaded files
- link to the file when clicking on the file 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.19.2
- Bootstrap 4
Setup Vue File Upload Project
Open cmd at the folder you want to save Project folder, run command:
vue create vue-upload-files
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.
– UploadFiles component contains upload form, progress bar, display of list files.
– 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 Files
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 Files
Let’s create a File Upload UI with Progress Bar, Card, Button and Message.
First we create a Vue component template and import UploadFilesService
:
components/UploadFiles.vue
<template>
</template>
<script>
import UploadService from "../services/UploadFilesService";
export default {
name: "upload-files",
data() {
return {
};
},
methods: {
}
};
</script>
Then we define the some variables inside data()
export default {
name: "upload-files",
data() {
return {
selectedFiles: undefined,
currentFile: undefined,
progress: 0,
message: "",
fileInfos: []
};
},
};
Next we define selectFile()
method which helps us to get the selected Files from ref="file"
element in HTML template later.
export default {
name: "upload-files",
...
methods: {
selectFile() {
this.selectedFiles = this.$refs.file.files;
}
}
};
We also define upload()
method for upload file:
export default {
name: "upload-files",
...
methods: {
...
upload() {
this.progress = 0;
this.currentFile = this.selectedFiles.item(0);
UploadService.upload(this.currentFile, event => {
this.progress = Math.round((100 * event.loaded) / event.total);
})
.then(response => {
this.message = response.data.message;
return UploadService.getFiles();
})
.then(files => {
this.fileInfos = files.data;
})
.catch(() => {
this.progress = 0;
this.message = "Could not upload the file!";
this.currentFile = undefined;
});
this.selectedFiles = undefined;
}
}
};
We use selectedFiles
for accessing current File as the first Item. Then we call UploadService.upload()
method on the currentFile
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 files’ information and assign the result to fileInfos
variable.
Here, fileInfos
is an array of {name, url}
objects.
We also need to do this work in mounted()
method:
export default {
name: "upload-files",
...
mounted() {
UploadService.getFiles().then(response => {
this.fileInfos = response.data;
});
}
};
Now we implement the HTML template of the Upload File UI. Add the following content to <template>
:
<template>
<div>
<div v-if="currentFile" class="progress">
<div
class="progress-bar progress-bar-info progress-bar-striped"
role="progressbar"
:aria-valuenow="progress"
aria-valuemin="0"
aria-valuemax="100"
:style="{ width: progress + '%' }"
>
{{ progress }}%
</div>
</div>
<label class="btn btn-default">
<input type="file" ref="file" @change="selectFile" />
</label>
<button class="btn btn-success" :disabled="!selectedFiles" @click="upload">
Upload
</button>
<div class="alert alert-light" role="alert">{{ message }}</div>
<div class="card">
<div class="card-header">List of Files</div>
<ul class="list-group list-group-flush">
<li
class="list-group-item"
v-for="(file, index) in fileInfos"
:key="index"
>
<a :href="file.url">{{ file.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
Add Upload File Component to App Component
Open App.vue and embed the UploadFiles
Component with <upload-files>
tag.
<template>
<div id="app">
<div class="container" style="width:600px">
<div style="margin: 20px">
<h3>bezkoder.com</h3>
<h4>Vue.js upload Files</h4>
</div>
<upload-files></upload-files>
</div>
</div>
</template>
<script>
import UploadFiles from "./components/UploadFiles";
export default {
name: "App",
components: {
UploadFiles
}
};
</script>
Configure Port for Vue File Upload App
Because most of HTTP Server use CORS configuration that accepts resource sharing restricted to some sites or ports. And if you use the Project in this post for making Server, 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
Run this Vue File 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 Files using Vue and Axios. We also provide the ability to show list of files, upload progress with Bootstrap, and to download file 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 for File Upload with the tutorial:
Vuetify File Upload example
Or Image upload:
Vue upload image using Axios (with Preview)
Source code
The source code for this Vue Client is uploaded to Github.
Hi, good vue example thanks.
this file upload example is it possible to use with springboot example with JWT applied?
Help me its got err_connection_refused
Hi, you need to run one of the backend servers I show in the tutorial first.
Thanks!
Like!! Really appreciate you sharing this Vue tutorial. Really thank you! Keep writing.
You are great, your example works for me thank you, please what is your twitter account to follow you thanks!