当前位置:首页 > JavaScript

js实现上传进度条

2026-03-01 03:35:39JavaScript

实现上传进度条的方法

XMLHttpRequest 方法

使用 XMLHttpRequest 对象的 upload 属性监听进度事件。XMLHttpRequest 提供了 progress 事件,可以实时获取上传进度。

const xhr = new XMLHttpRequest();
const fileInput = document.getElementById('fileInput');
const progressBar = document.getElementById('progressBar');

xhr.upload.addEventListener('progress', (event) => {
  if (event.lengthComputable) {
    const percentComplete = (event.loaded / event.total) * 100;
    progressBar.style.width = `${percentComplete}%`;
    progressBar.textContent = `${Math.round(percentComplete)}%`;
  }
});

xhr.open('POST', '/upload', true);
xhr.send(new FormData(fileInput));

Fetch API 方法

Fetch API 本身不直接支持进度跟踪,但可以通过 ReadableStreamTransformStream 实现类似功能。

const fileInput = document.getElementById('fileInput');
const progressBar = document.getElementById('progressBar');

async function uploadWithProgress(file) {
  const reader = file.stream().getReader();
  let totalUploaded = 0;

  const stream = new ReadableStream({
    async pull(controller) {
      const { done, value } = await reader.read();
      if (done) {
        controller.close();
        return;
      }
      totalUploaded += value.length;
      const percentComplete = (totalUploaded / file.size) * 100;
      progressBar.style.width = `${percentComplete}%`;
      progressBar.textContent = `${Math.round(percentComplete)}%`;
      controller.enqueue(value);
    }
  });

  await fetch('/upload', {
    method: 'POST',
    headers: { 'Content-Type': 'application/octet-stream' },
    body: stream
  });
}

fileInput.addEventListener('change', () => {
  uploadWithProgress(fileInput.files[0]);
});

Axios 方法

Axios 提供了 onUploadProgress 回调函数,可以方便地跟踪上传进度。

const axios = require('axios');
const fileInput = document.getElementById('fileInput');
const progressBar = document.getElementById('progressBar');

const uploadFile = (file) => {
  const formData = new FormData();
  formData.append('file', file);

  axios.post('/upload', formData, {
    onUploadProgress: (progressEvent) => {
      const percentComplete = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      progressBar.style.width = `${percentComplete}%`;
      progressBar.textContent = `${percentComplete}%`;
    }
  });
};

fileInput.addEventListener('change', () => {
  uploadFile(fileInput.files[0]);
});

使用第三方库

一些第三方库如 uppydropzone 提供了内置的上传进度功能。

js实现上传进度条

const uppy = new Uppy({
  restrictions: {
    maxFileSize: 1000000,
    maxNumberOfFiles: 3,
    allowedFileTypes: ['image/*']
  }
});

uppy.use(Dashboard, {
  inline: true,
  target: '#upload-container'
});

uppy.use(XHRUpload, {
  endpoint: '/upload',
  fieldName: 'file'
});

uppy.on('upload-progress', (file, progress) => {
  console.log(file.id, progress.percent);
});

注意事项

  • 确保服务器支持分块上传或正确处理上传进度。
  • 对于大文件上传,考虑使用分块上传以减少内存占用。
  • 跨域请求时,服务器需要配置 CORS 头部以允许进度事件。

以上方法可以根据项目需求和技术栈选择适合的实现方式。

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

相关文章

vue实现语音上传

vue实现语音上传

实现语音上传功能 在Vue中实现语音上传功能需要结合浏览器的Web Audio API和文件上传逻辑。以下是一个完整的实现方案: 录音功能实现 安装依赖库recorder-core和wav编码器:…

vue实现附件上传

vue实现附件上传

文件上传的基本实现 在Vue中实现文件上传可以通过原生HTML的<input type="file">元素结合Vue的数据绑定和事件处理来完成。创建一个文件上传组件,监听change事件获…

vue实现音乐上传

vue实现音乐上传

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

vue实现进度条

vue实现进度条

Vue 实现进度条的方法 使用原生 HTML 和 CSS 结合 Vue 数据绑定 创建一个简单的进度条,通过 Vue 的数据绑定动态控制进度值。 <template> <div…

vue上传文档怎么实现

vue上传文档怎么实现

使用原生 <input type="file"> 实现上传 在 Vue 模板中添加一个文件输入框,绑定 change 事件处理文件选择: <input type="file" @c…

vue怎么实现视频上传

vue怎么实现视频上传

实现视频上传功能 在Vue中实现视频上传功能通常需要结合HTML5的<input type="file">元素和后端API。以下是实现方法: 前端实现 创建文件上传组件模板: <…