纯oss链接下载,得先把链接转为blob 的流数据,然后才能进行自定义改名字😒*😂

221 阅读1分钟

第一种下载的方法(较为麻烦)

//下载文件并重命名
export function downloadFileRename(url, filename) {
  function getBlob(url) {
    return new Promise((resolve) => {
      const xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response)
        }
      }
      xhr.send()
    })
  }
  function saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename)
    } else {
      const link = document.createElement('a')
      const exportBtn = document.getElementById('exportBtn')

      link.href = window.URL.createObjectURL(blob)
      link.download = filename

      // fix Firefox
      link.style.display = 'none'
      exportBtn.appendChild(link)

      link.click()
      exportBtn.removeChild(link)

      window.URL.revokeObjectURL(link.href)
      return
    }
  }
  getBlob(url).then((blob) => {
    saveAs(blob, filename)
  })
}

第二种方法

async function downLoadFile (url,filename){
    try{
    // 获取文件并转换为Blob
    const response = await fetch(url); 
    const blob = await response.blob(); 通常 `response.blob()` 会自动处理 MIME 类型也就是responseType     
    //创建一个临时的URL供下载使用
    const url = URL.createObjectURL(blob);
    
    创建一个下载链接并模拟点击
    const link = document.createElement('a');
    link.href = url;
    link.download = filename; // 设置下载的文件名
    document.body.appendChild(link); // 将链接添加到文档中
    link.click() // 模拟点击下载
    document.body.remoceChild(link) // 下载后移除链接
    
    // 释放临时url
    URL.revokeObjectURL(url);
}catch(error){
    console.log('下载文件失败',error);
}