Home Web Front-end Vue.js How to implement file upload function in Vue?

How to implement file upload function in Vue?

Jun 25, 2023 pm 01:38 PM
vue File Upload accomplish

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>
Copy after login

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>
Copy after login

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"
Copy after login

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}`);
});
Copy after login

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"
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles