search
HomeWeb Front-endVue.jsHow to implement file upload function in Vue?

Vue is currently one of the most popular frameworks for front-end development, and its way of implementing the file upload function is also very simple and elegant. This article will introduce how to implement the file upload function in Vue.

  1. HTML part

Add the following code in the HTML file to create the upload form:

<template>
  <div>
    <form ref="uploadForm" 
          enctype="multipart/form-data" 
          class="upload-form" 
          @submit.prevent="submitFile">
      <input type="file" 
             name="file" 
             id="file" 
             class="input-file"
             ref="file"
             @change="handleFileChange" />
      <label for="file" class="btn">选择文件</label>
      <!-- 进度条展示 -->
      <p v-if="showProgress">上传进度:{{ percent }} %</p>
      <button type="submit" 
              class="upload-btn" 
              :disabled="!selectedFile">上传</button>
    </form>
  </div>
</template>

In the above code, use the form and input tags to create it Upload form. The name attribute in the upload form specifies the field name of the file in the form. The enctype attribute indicates the type of file to be uploaded. The multipart/form-data type is used here.

In the label label, use the @click.prevent event to trigger the click event of the input label, thereby popping up the file selection box. The @change event here can listen to the file selection and call the handleFileChange method to update the file name in the form.

  1. JavaScript part

In the JavaScript file, we need to implement file upload through the custom component of Vue.js and the axios library.

<script>
import axios from 'axios';

export default {
  data () {
    return {
      selectedFile: null,  // 选中的文件
      showProgress: false,  // 是否展示上传进度条
      percent: 0,    // 上传进度百分比
    }
  },
  methods: {
    handleFileChange (event) {
      this.selectedFile = event.target.files[0];
    },
    submitFile () {
      if (!this.selectedFile) return;
      // 新建 from 对象
      const formData = new FormData();
      formData.append('file', this.selectedFile, this.selectedFile.name);

      this.showProgress = true;
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          // 计算上传进度百分比
          this.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        },
      };
      axios.post('/api/upload', formData, config)
        .then((response) => {
          console.log(response);
          this.showProgress = false;  // 移除 progress 条
        })
        .catch((error) => {
          console.log(error);
          this.showProgress = false;
        });
    },
  },
};
</script>

Define handleFileChange() and submitFile() methods in methods to handle file selection and upload:

  • handleFileChange method listens to the file selection event and stores the selected file.
  • The submitFile method determines whether the selected file exists. If it does not exist, it will be returned directly. Use new FormData() to construct a form, and append the selected file to the form through the append method. Note that the third parameter is the file name. axios.post specifies the API for uploading files through string parameters. The data requested for upload is the formData object. The Content-Type attribute in Headers specifies the data type. The multipart/form-data type is used here, and the upload is monitored through the onUploadProgress event. Progress in order to achieve dynamic display of the progress bar.

In the above code, we use the axios library to complete the file upload operation. Add the dependency of axios in the package.json file of the front-end project:

"axios": "^0.19.2"

Introduce and use it through import axios from 'axios';. In the backend API, use the Multer library to handle file uploads. Multer is a Node.js library that handles file uploads. Multer can process files and send them along with the form.

  1. Backend API part
const express = require('express');
const multer = require('multer');
const fs = require('fs');

const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/api/upload', upload.single('file'), (req, res) => {
  const file = req.file;
  if (!file) {
    const error = new Error('Please upload a file');
    error.httpStatusCode = 400;
    return next(error);
  }
  // 文件重命名
  const oldPath = file.path;
  const newPath = 'uploads/' + file.originalname;
  fs.rename(oldPath, newPath, (err) => {
    if (err) {
      console.error(err);
    }
  });
  res.send('File uploaded successfully');
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

The field name of the uploaded file is specified through Multer's single method. Multer also provides other methods for multi-file upload and file type restrictions. Wait for operations. After the upload is completed, we will move the file from the initial path to the uploads directory. The file renaming operation can make the name unique and avoid overwriting by uploading different file names.

In the above code, we use the express library to create a Node.js server application. Add the following dependencies to the package.json file in the background project:

"express": "^4.17.1",
"multer": "^1.4.2"

Use the import / require statement to introduce and use the corresponding module.

  1. Exception handling

During the file upload process, abnormal situations may occur, such as file size exceeding the limit, file type not allowed, network timeout and server error and other factors, we need to write corresponding exception handlers for the client and server.

In the client part, since we use the axios library, we can directly use the then and catch methods to process the Promise object returned by the upload request, and handle the operations when the upload is successful and failed respectively. In the code provided in this article, we use Promise.catch() to handle exceptions during process execution. On the server side, different exceptions require different handling based on the actual situation.

  1. Summary

In this article, we introduced how to use Vue.js to complete the file upload operation, including front-end file selection and dynamic display of the progress bar during the upload process. As well as the preparation of background APIs, and handling of abnormal situations that may occur during the upload process.

The file upload function is an indispensable feature in many web applications. Using the axios library and Multer library in Vue.js can achieve a simple and elegant upload process.

The above is the detailed content of How to implement file upload function in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft