Home  >  Article  >  Web Front-end  >  How to implement file upload function in Vue?

How to implement file upload function in Vue?

WBOY
WBOYOriginal
2023-06-25 13:38:5812198browse

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