可以使用axios库来下载文件,并且支持大文件下载和流式下载。具体代码如下:

  1. 普通文件下载
import axios from 'axios'

// 后台返回的文件路径
const url = 'http://example.com/file.pdf'

axios({
  url: url,
  method: 'GET',
  responseType: 'blob' // 表示返回的数据类型为二进制流
}).then(response => {
  const blob = new Blob([response.data])
  const href = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = href
  link.download = 'file.pdf'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
})
  1. 大文件下载并显示进度
import axios from 'axios'

// 后台返回的文件路径
const url = 'http://example.com/file.zip'

axios({
  url: url,
  method: 'GET',
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    // 计算下载进度百分比
    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
    console.log(percentCompleted)
  }
}).then(response => {
  const blob = new Blob([response.data])
  const href = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = href
  link.download = 'file.zip'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
})
  1. 流式下载
import axios from 'axios'

// 后台返回的文件路径
const url = 'http://example.com/largefile.zip'

axios({
  url: url,
  method: 'GET',
  responseType: 'stream' // 表示返回的数据类型为流
}).then(response => {
  const stream = response.data
  const blob = new Blob([stream], { type: 'application/octet-stream' })
  const href = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = href
  link.download = 'largefile.zip'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
})
``
vue30 后台给文件路径 前端怎么写好下载 才是最优 请提供下代码 怎么写也支持大文件下载并显示进度 流式下载怎么写

原文地址: https://www.cveoy.top/t/topic/dUca 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录