MST

星途 面试题库

面试题:Vue 中如何实现文件上传并处理进度条

在 Vue 项目里,要求使用 axios 实现文件上传功能,并实时显示上传进度条。请描述实现思路并给出关键代码片段。
39.5万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 安装 axios:如果项目未安装,通过 npm 或 yarn 安装 axios
  2. 创建表单数据:使用 FormData 对象来构造要上传的文件数据。
  3. 发送请求并监听进度:在 axios 的 config 中设置 onUploadProgress 回调函数,用于监听上传进度。
  4. 更新进度条:在 onUploadProgress 回调函数中,计算并更新进度条的显示。

关键代码片段

<template>
  <div>
    <input type="file" @change="handleFileChange">
    <div v-if="uploading">
      <progress :value="progress" :max="100"></progress>
      <p>{{ progress }}%</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      uploading: false,
      progress: 0
    };
  },
  methods: {
    handleFileChange(e) {
      this.file = e.target.files[0];
      this.uploadFile();
    },
    uploadFile() {
      this.uploading = true;
      const formData = new FormData();
      formData.append('file', this.file);

      axios.post('/upload', formData, {
        onUploadProgress: progressEvent => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          this.progress = percentCompleted;
        }
      })
      .then(response => {
          // 上传成功处理
          this.uploading = false;
          this.progress = 0;
          console.log('文件上传成功', response.data);
        })
      .catch(error => {
          // 上传失败处理
          this.uploading = false;
          this.progress = 0;
          console.error('文件上传失败', error);
        });
    }
  }
};
</script>