Home > Article > Web Front-end > Examples to explain how Vue implements the file upload function
Vue is a popular JavaScript framework that is widely used in front-end development. In Vue, file upload is a very common requirement. This article will introduce how to write Vue upload files.
1. Installation dependencies
Vue file upload requires the use of axios and vue-router, so we need to install these two dependencies:
npm install axios vue-router --save
2. HTML Code
The following is the HTML code for Vue to upload files:
<template> <div> <input type="file" @change="onFileChange" /> <button @click="upload">上传</button> </div> </template>
Among them, onFileChange is an event triggered when a file is selected, and upload is an event triggered when the upload button is clicked.
3. JavaScript code
Next, we need to write Vue’s JavaScript code:
<script> import axios from 'axios' import router from 'vue-router' export default { name: 'file-upload', data () { return { file: null, errorMsg: '' } }, methods: { onFileChange (event) { this.file = event.target.files[0]; }, upload () { let formData = new FormData(); formData.append('file', this.file); let token = localStorage.getItem('token'); if (token) { axios.post('/api/upload', formData, { headers: { 'Authorization': 'Bearer ' + token } }) .then(response => { router.push('/success'); }) .catch(error => { this.errorMsg = '上传文件失败'; }) } } } } </script>
Among them, we first import axios and vue-router dependencies, and then define A data object contains two attributes: file and errorMsg, which represent files and error messages respectively.
Next, we defined two methods: onFileChange and upload. The onFileChange method is triggered when a file is selected and saves the selected file in the file attribute of the data object. The upload method is triggered when the upload button is clicked. First, a FormData object is created, and then the file is uploaded to the server through the axios.post method. After the upload is successful, vue-router is used to jump to the success page. An error occurs during the upload process. The errorMsg attribute is assigned a value of failure to upload the file.
4. Summary
The writing method of Vue uploading files is relatively simple. You only need to understand the usage of two dependencies, axios and vue-router, to realize the file upload function. I hope the introduction in this article can be helpful to everyone.
The above is the detailed content of Examples to explain how Vue implements the file upload function. For more information, please follow other related articles on the PHP Chinese website!