vue文件下载

 blob方式:

const handleDownloadBlob = async(id) => {
  const res = await downLoadBlob(id).then(data => {
    return data;
  }) .catch(err => {
    console.log(err)
  });
  debugger
  if (res) {
    ElMessage({message: '正在下载!', type: 'success',});

    const blob = new Blob([res.data], { type: res.data.type })  //创建一个blob
    let i = res['content-disposition'].indexOf("=")
    let filename = res['content-disposition'].substr(i + 1)  // 文件名
    if (window.navigator && window.navigator.msSaveBlob) {
      navigator.msSaveBlob(blob, filename)
    } else {
      const a = document.createElement('a')     //创建一个a链接
      const url = window.URL.createObjectURL(blob)
      a.href = url  //创建a连接的href
      a.download = filename //设置名称
      a.click()   //点击事件
      window.URL.revokeObjectURL(url) //释放url对象
    }
  }
}

直接使用a标签赋值URL链接方式:

const fileUrl = baseUrl + 'biz/file/download/' + id;
  const link = document.createElement('a');
  link.href = fileUrl;
  link.click();

下载文件:

const loadFile = (downloadUrl) =>{
  const xhr = new XMLHttpRequest()
  const okStatus = document.location.protocol === 'file:' ? 0 : 200
  xhr.open('GET', downloadUrl, false)
  xhr.overrideMimeType('text/html;charset=utf-8')
  // 默认为utf-8
  xhr.send(null)
  return xhr.status === okStatus ? xhr.responseText : null
}

你可能感兴趣的:(vue.js,javascript,前端)