Vue 下载文件

316 阅读1分钟

开发中难免很多下载需求,各个项目经常使用,以下是开发 Vue 里面,自己使用的下载文件方式,如有更好的推荐,请各位不吝赐教

下载图片

1. 单个图片下载

function downloadImg(url, name) {
  let image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = url
  image.onload = () => {
    let canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0, image.width, image.height)
    canvas.toBlob(blob => {
      let url = URL.createObjectURL(blob)
      download(url, name)
      // 用完释放URL对象
      URL.revokeObjectURL(url)
    })
  }
}

function download(href, name) {
  let eleLink = document.createElement('a')
  eleLink.download = name
  eleLink.href = href
  eleLink.click()
  eleLink.remove()
}

下载文件

export function exportExcel(
  params,
  type = 'get',
  url = '/api/crm/export/exportGrowthRecord'
) {
  // 导出表格
  const temConfig = {
    headers: {
      'Content-Type': 'application/json; application/octet-stream',
      token
    },
    params,
    responseType: 'blob' // 要点需要返回类型
  }
  return new Promise((resolve, reject) => {
    axios[type]('/api' + url, temConfig).then(res => {
      if (res.status === 200) {
        let blob = new Blob([res.data], {
          // 这里一定要和后端对应,不然可能出现乱码或者打不开文件
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const fname = res.headers['content-disposition'].split('=')[1] // 下载文件的名字

        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fname)
        } else {
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fname // 在前端也可以设置文件名字
          link.click()
          window.URL.revokeObjectURL(link.href)
        }
      } else {
        Message({
          type: 'error',
          message: '导出失败'
        })
      }
    })
  })
}