当前位置:首页 > VUE

vue实现下载暂停

2026-03-27 03:04:19VUE

Vue实现下载暂停功能

在Vue中实现下载暂停功能,可以通过XMLHttpRequest或Fetch API结合AbortController来控制下载过程。以下是具体实现方法:

使用XMLHttpRequest实现

XMLHttpRequest对象提供了直接控制请求的能力,可以通过其abort()方法暂停下载。

// 在Vue组件中
data() {
  return {
    xhr: null,
    isDownloading: false
  }
},
methods: {
  startDownload() {
    this.isDownloading = true
    this.xhr = new XMLHttpRequest()
    this.xhr.open('GET', 'your-file-url', true)
    this.xhr.responseType = 'blob'

    this.xhr.onprogress = (event) => {
      // 更新下载进度
      const progress = Math.round((event.loaded / event.total) * 100)
      console.log(`下载进度: ${progress}%`)
    }

    this.xhr.onload = (event) => {
      const blob = new Blob([this.xhr.response])
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'filename.ext'
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      this.isDownloading = false
    }

    this.xhr.send()
  },

  pauseDownload() {
    if (this.xhr && this.isDownloading) {
      this.xhr.abort()
      this.isDownloading = false
      console.log('下载已暂停')
    }
  }
}

使用Fetch API和AbortController实现

Fetch API配合AbortController提供了更现代的暂停下载方式。

// 在Vue组件中
data() {
  return {
    controller: null,
    isDownloading: false
  }
},
methods: {
  async startDownload() {
    this.isDownloading = true
    this.controller = new AbortController()

    try {
      const response = await fetch('your-file-url', {
        signal: this.controller.signal
      })

      const reader = response.body.getReader()
      const contentLength = +response.headers.get('Content-Length')
      let receivedLength = 0
      let chunks = []

      while(true) {
        const {done, value} = await reader.read()
        if(done) break

        chunks.push(value)
        receivedLength += value.length
        const progress = Math.round((receivedLength / contentLength) * 100)
        console.log(`下载进度: ${progress}%`)
      }

      const blob = new Blob(chunks)
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'filename.ext'
      document.body.appendChild(a)
      a.click()
      URL.revokeObjectURL(url)
      this.isDownloading = false
    } catch (err) {
      if (err.name === 'AbortError') {
        console.log('下载已暂停')
      } else {
        console.error('下载错误:', err)
      }
    }
  },

  pauseDownload() {
    if (this.controller && this.isDownloading) {
      this.controller.abort()
      this.isDownloading = false
    }
  }
}

实现断点续传

要实现更高级的暂停后继续下载功能(断点续传),需要服务器支持Range请求。

vue实现下载暂停

// 在Vue组件中
methods: {
  async resumeDownload() {
    const fileSize = await this.getFileSize()
    const downloadedSize = this.getLocalFileSize() // 从本地存储获取已下载大小

    const response = await fetch('your-file-url', {
      headers: {
        'Range': `bytes=${downloadedSize}-`
      }
    })

    // 处理响应并追加到已有文件
  },

  async getFileSize() {
    const response = await fetch('your-file-url', {
      method: 'HEAD'
    })
    return response.headers.get('Content-Length')
  }
}

注意事项

  • 服务器必须支持CORS,否则可能无法获取进度信息
  • 断点续传需要服务器支持Range请求头
  • 暂停后已下载的部分需要本地存储(如localStorage或IndexedDB)
  • 大文件下载建议使用分块下载策略

以上方法可根据实际需求选择使用,XMLHttpRequest兼容性更好,而Fetch API更现代且语法更简洁。

标签: vue
分享给朋友:

相关文章

vue插件实现

vue插件实现

Vue 插件实现方法 Vue 插件是一种向 Vue 应用程序添加全局功能的机制。插件可以包含全局指令、过滤器、混入、实例方法等。 插件的基本结构 一个 Vue 插件通常是一个对象或函数,需要暴露一个…

vue 全景实现

vue 全景实现

Vue 全景实现方案 在Vue中实现全景效果,通常需要结合WebGL或第三方库来处理3D场景渲染。以下是几种常见方法: 使用Three.js库 Three.js是一个强大的WebGL库,适合创建3D…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template&…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单文…

vue实现treeselect

vue实现treeselect

Vue TreeSelect 实现方法 使用 Vue 实现 TreeSelect 组件可以通过以下几种方式完成,包括使用现成的第三方库或自行封装组件。 使用第三方库 推荐使用成熟的第三方 TreeS…

vue实现微云

vue实现微云

Vue 实现微云功能 使用 Vue 实现类似微云的网盘功能需要结合前端框架、后端存储及文件处理技术。以下是关键实现步骤和代码示例: 前端框架搭建 使用 Vue CLI 创建项目基础结构,安装必要依赖…