How to Upload File in Vue and Axios

In this tutorial, I volition evidence you lot way to build a Vue File Upload case that uses Axios and Multipart File for making HTTP requests. You volition also know how to add Bootstrap progress bar, show response bulletin and display list of files' data (with url).

More than Practice:
– Vue upload Image using Axios (with Preview)
– Vue Multiple Files Upload with Axios, FormData and Progress Bars
– Vue.js ii Crud Application with Vue Router & Axios
– Vue.js JWT Authentication with Vuex and Vue Router
– Vue Pagination with Axios and API instance

Using Vuetify: Vuetify File Upload example

Overview

We're gonna create a Vue File upload application in that user can:

  • see the upload process (per centum)
  • view all uploaded files
  • link to the file when clicking on the file name

vue-axios-file-upload-example-demo

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

Methods Urls Deportment
Postal service /upload upload a File
GET /files go List of Files (name & url)
GET /files/[filename] download a File

You can find how to implement the Rest APIs Server at one of post-obit 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 case
– Spring Boot Multipart File upload (to static folder) example

Or: Bound Boot Multipart File upload (to database) example

Applied science

  • Vue ii.half-dozen
  • Axios 0.nineteen.2
  • Bootstrap 4

Setup Vue File Upload Projection

Open up cmd at the binder yous desire to save Project folder, run command:
vue create vue-upload-files

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

So we add Axios library with control: npm install axios.

Structure the Project

After the process is done. Nosotros create new folders and files like this:

vue-axios-file-upload-example-project-structure

UploadFilesService provides methods to salve File and go Files using Axios.
UploadFiles component contains upload course, progress bar, display of list files.
App.vue is the container that we embed all Vue components.

alphabetize.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 alphabetize.html and add following line into <head> tag:

          <!DOCTYPE html> <html lang="en">   <caput>     ...     <link type="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/iv.four.1/css/bootstrap.min.css" />   </head>   ... </html>                  

Initialize Axios for Vue HTTP Client

Nether src binder, 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"   } });                  

Recollect 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 ship HTTP requests.
There are 2 functions:

  • upload(file): POST course data with a callback for tracking upload progress
  • getFiles(): Get listing of Files' data

services/UploadFilesService.js

          import http from "../http-mutual"; 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");   } } consign default new UploadFilesService();                  

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

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

– We laissez passer onUploadProgress to exposes progress events. This progress upshot are expensive (change detection for each event), so you lot should simply employ when you desire to monitor it.

– Nosotros call the postal service() & become() method of Axios to send an HTTP Mail & Get request to the File Upload server.

Create Component for Upload Files

Let'due south create a File Upload UI with Progress Bar, Carte du jour, Button and Message.

Outset we create a Vue component template and import UploadFilesService:

components/UploadFiles.vue

          <template> </template> <script> import UploadService from "../services/UploadFilesService"; export default {   proper name: "upload-files",   data() {     return {     };   },   methods: {      } }; </script>                  

So we define the some variables inside data()

          export default {   proper noun: "upload-files",   data() {     render {       selectedFiles: undefined,       currentFile: undefined,       progress: 0,       message: "",       fileInfos: []     };   }, };                  

Side by side nosotros ascertain selectFile() method which helps united states of america to get the selected Files from ref="file" element in HTML template afterward.

          export default {   name: "upload-files",   ...   methods: {     selectFile() {       this.selectedFiles = this.$refs.file.files;     }   } };                  

We also define upload() method for upload file:

          export default {   proper noun: "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.information.message;           return UploadService.getFiles();         })         .then(files => {           this.fileInfos = files.data;         })         .catch(() => {           this.progress = 0;           this.bulletin = "Could not upload the file!";           this.currentFile = undefined;         });       this.selectedFiles = undefined;     }   } };                  

We use selectedFiles for accessing current File as the first Item. Then nosotros call UploadService.upload() method on the currentFile with a callback.

The progress will be calculated basing on consequence.loaded and consequence.total.
If the transmission is washed, nosotros phone call UploadService.getFiles() to become the files' information and assign the result to fileInfos variable.

Hither, fileInfos is an array of {name, url} objects.

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

          export default {   name: "upload-files",   ...   mounted() {     UploadService.getFiles().then(response => {       this.fileInfos = response.information;     });   } };                  

Now we implement the HTML template of the Upload File UI. Add the post-obit content to <template>:

          <template>   <div>     <div 5-if="currentFile" class="progress">       <div         grade="progress-bar progress-bar-info progress-bar-striped"         role="progressbar"         :aria-valuenow="progress"         aria-valuemin="0"         aria-valuemax="100"         :manner="{ width: progress + '%' }"       >         {{ progress }}%       </div>     </div>     <label class="btn btn-default">       <input type="file" ref="file" @modify="selectFile" />     </label>     <button grade="btn btn-success" :disabled="!selectedFiles" @click="upload">       Upload     </button>     <div class="alert warning-lite" role="alert">{{ message }}</div>     <div class="card">       <div grade="card-header">List of Files</div>       <ul class="list-group listing-grouping-affluent">         <li           form="list-grouping-item"           five-for="(file, index) in fileInfos"           :central="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 betoken the progress
  • .progress-bar requires style to set the width past per centum
  • .progress-bar as well requires part 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 mode="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 y'all use the Project in this postal service for making Server, y'all demand to configure port for our App.

In src folder, create vue.config.js file with post-obit content:

          module.exports = {   devServer: {     port: 8081   } }                  

Nosotros've set our app running at port 8081. vue.config.js volition 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 cheque the upshot.

Farther Reading

  • https://github.com/axios/axios
  • Vue.js 2 CRUD Awarding with Vue Router & Axios

Fullstack CRUD App:

  • Vue.js + Node.js + Express + MySQL
  • Vue.js + Node.js + Express + PostgreSQL
  • Vue.js + Node.js + Limited + 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

Decision

Today nosotros're learned how to build an example for upload Files using Vue and Axios. We besides provide the ability to show listing of files, upload progress with Bootstrap, and to download file from the server.

You lot tin can find how to implement the Balance APIs Server at 1 of post-obit 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 instance
– Leap Boot Multipart File upload (to static folder) example

Or: Spring Boot Multipart File upload (to database) example

If yous want to upload multiple files like this:

vue-js-multiple-file-upload-axios-formdata-progress-bar

Please visit:
Vue Multiple Files Upload with Axios, FormData and Progress Confined

Or utilize 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 lawmaking for this Vue Client is uploaded to Github.

hughes-jonesawitin.blogspot.com

Source: https://www.bezkoder.com/vue-axios-file-upload/

0 Response to "How to Upload File in Vue and Axios"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel