当前位置:首页 > VUE

vue实现下载暂停

2026-03-27 03:04:19VUE

Vue实现下载暂停功能

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

vue实现下载暂停

使用XMLHttpRequest实现

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

vue实现下载暂停

// 在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组件中
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.js 作为前端框架,非常适合实现前后端分离的开发模式。 核心实现步骤 创建 Vue 项目 使用…

vue 方法实现

vue 方法实现

在 Vue 中,方法的实现通常通过 methods 选项完成。以下是 Vue 方法实现的核心要点和示例: 基本方法定义 在 Vue 组件中定义方法时,需将函数声明放在 methods 对象内。这些方…

vue实现增删

vue实现增删

Vue 实现增删功能 在 Vue 中实现增删功能通常涉及数据绑定、事件处理和列表渲染。以下是基于 Vue 2 或 Vue 3 的实现方法: 数据定义 初始化一个数组用于存储列表数据,并在 Vue 实…

vue实现计数

vue实现计数

Vue 实现计数功能 在 Vue 中实现计数功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue 数据绑定和事件监听 通过 Vue 的数据绑定和事件监听,可以轻松实现计数功能。以下是一个简…

vue实现修改

vue实现修改

Vue 实现修改功能的方法 在 Vue 中实现修改功能通常涉及表单绑定、状态管理和 API 调用。以下是几种常见实现方式: 双向数据绑定实现表单修改 使用 v-model 指令绑定表单元素与组件数据…

vue实现购物平台

vue实现购物平台

实现购物平台的基本架构 使用Vue.js构建购物平台需要结合前端框架、状态管理、路由和后端接口。以下是一个基本实现方案: 项目初始化与依赖安装 通过Vue CLI创建项目并安装必要依赖: vue…