当前位置:首页 > VUE

vue实现上传进度

2026-01-17 08:04:16VUE

Vue 实现文件上传进度

在 Vue 中实现文件上传进度可以通过 XMLHttpRequestaxiosonUploadProgress 事件来监听上传进度。以下是两种常见实现方式:

使用 XMLHttpRequest 实现

通过原生 XMLHttpRequest 对象的 upload 属性监听进度事件:

// 在 Vue 方法中
uploadFile(file) {
  const xhr = new XMLHttpRequest();
  const formData = new FormData();
  formData.append('file', file);

  xhr.upload.addEventListener('progress', (event) => {
    if (event.lengthComputable) {
      const percent = Math.round((event.loaded / event.total) * 100);
      this.uploadProgress = percent; // 更新进度状态
    }
  });

  xhr.open('POST', '/api/upload', true);
  xhr.send(formData);
}

模板中显示进度:

<progress :value="uploadProgress" max="100"></progress>
<span>{{ uploadProgress }}%</span>

使用 Axios 实现

Axios 提供了 onUploadProgress 回调,更适合 Vue 项目:

import axios from 'axios';

// 在 Vue 方法中
async uploadFile(file) {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await axios.post('/api/upload', formData, {
      onUploadProgress: (progressEvent) => {
        const percent = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        this.uploadProgress = percent;
      },
    });
    console.log('上传成功', response.data);
  } catch (error) {
    console.error('上传失败', error);
  }
}

组件化实现示例

封装一个可复用的上传组件:

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">上传</button>
    <div v-if="uploadProgress > 0">
      <progress :value="uploadProgress" max="100"></progress>
      {{ uploadProgress }}%
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedFile: null,
      uploadProgress: 0,
    };
  },
  methods: {
    handleFileChange(event) {
      this.selectedFile = event.target.files[0];
    },
    async uploadFile() {
      if (!this.selectedFile) return;

      const formData = new FormData();
      formData.append('file', this.selectedFile);

      try {
        await axios.post('/api/upload', formData, {
          onUploadProgress: (progressEvent) => {
            this.uploadProgress = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
          },
        });
        this.$emit('upload-success');
      } catch (error) {
        this.$emit('upload-error', error);
      }
    },
  },
};
</script>

注意事项

  1. 跨域问题:确保后端支持 CORS 并正确配置 Access-Control-Allow-Origin
  2. 文件大小限制:后端需处理大文件上传(如分片上传)。
  3. 进度准确性:部分服务器可能无法返回准确的 content-length,需测试验证。
  4. UI 反馈:建议结合加载状态或错误提示(如 v-if="uploadProgress === 100")。

通过上述方法,可以轻松在 Vue 中实现文件上传进度功能。

vue实现上传进度

标签: 进度上传
分享给朋友:

相关文章

vue实现拖拽上传

vue实现拖拽上传

Vue 拖拽上传实现方法 使用 HTML5 原生拖拽 API 在 Vue 中可以通过监听原生拖拽事件实现基础功能: <template> <div class="dr…

vue实现批量上传

vue实现批量上传

Vue 实现批量上传的方法 使用 <input type="file"> 和 multiple 属性 在 Vue 模板中添加一个文件输入框,设置 multiple 属性以允许选择多个文件。…

vue实现音乐上传

vue实现音乐上传

Vue 实现音乐上传功能 音乐上传功能通常涉及前端界面交互、文件选择、上传进度显示以及后端接口对接。以下是基于 Vue 的实现方法: 前端界面设计 使用 Vue 的模板语法创建一个简单的上传界面,包…

vue实现图片重新上传

vue实现图片重新上传

实现图片重新上传功能 在Vue中实现图片重新上传功能,通常涉及文件选择、预览、上传和重置等步骤。以下是一个完整的实现方案: 模板部分 <template> <div>…

vue java实现分片上传

vue java实现分片上传

分片上传的实现原理 分片上传是将大文件分割成多个小块分别上传,最后在服务器合并的技术。这种方式能解决大文件上传超时、网络不稳定等问题,同时支持断点续传。 前端Vue实现 前端需要使用File AP…

vue实现图片压缩上传

vue实现图片压缩上传

实现图片压缩上传的方法 使用HTML5的Canvas进行压缩 通过Canvas的drawImage和toDataURL方法实现图片压缩。创建一个input元素用于选择图片,监听change事件处理压缩…