前端下載文件

PC或者移動端下載文件(包括excel、圖片等)到本地

一、方案

根據(jù)平臺有不同的方案:

  • PC
    主要使用 window.open 方法,直接調(diào)用接口,接口返回文件直接下載

  • 移動端
    主要通過 file\img 轉(zhuǎn) base64,通過 a[download] 來下載

二、代碼實現(xiàn)

2.1 PC

如果下載接口需要登錄態(tài),且通過 cookie 傳遞

window.open(接口, '_blank');

如果下載接口需要登錄態(tài),且通過自定義 headers 字段傳遞

// 下載文件流
// axios 需要傳 responseType: 'blob',和 url data 平級
export function downloadTemplate(data = {}, headers = {}) {
  return request({
    url: '/web/addFriend/downloadTemplate',
    method: 'get',
    responseType: 'blob',
    data,
    headers
  })
}

// 使用 blob atag 進行下載
// 這里的 res 需要使用 axios 的整個 response,可以通過 response.headers['content-type'].indexOf('application/octet-stream') !== -1 判斷
function downloadFile(res) {
  const url = window.URL.createObjectURL(new Blob([res.data]))
  // 生成一個a標簽
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  // 生成文件名,并且去掉多余的雙引號
  const fileNameStr = res.headers['content-disposition'].split(';').find(item => item.indexOf('filename') !== -1)
  const fileName = fileNameStr ? fileNameStr.substring(fileNameStr.indexOf('=') + 1).replace(/\"/g, '') : Date.now()
  link.download = decodeURIComponent(fileName)
  link.click()
  link = null
}
// 這里需要判斷一下返回結(jié)果,因為有可能返回的是一個報錯
// 參考這篇文章 http://m.itdecent.cn/p/26f23345a4be

2.2 移動端

/**
 * URL 轉(zhuǎn) base64
 **/
convertImgToBase64 (url, callback) {
  return new Promise(resolve => {
    const img = new Image();
    // 圖片域名要開啟跨域
    // canvas 不能處理跨域圖片,執(zhí)行 canvas 操作前也要開啟跨域
    img.crossOrigin = 'Anonymous';
    img.onload = function() {
      let canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.height = this.height;
      canvas.width = this.width;
      ctx.drawImage(this, 0, 0);
      const imgBase64 = canvas.toDataURL("image/png");
      canvas = null;
      resolve(imgBase64);
    };
    img.src = url;
  })
},
// 下載
handleSave() {
  this.convertImgToBase64(this.url)
    .then(imgBase64 => {
      const a = document.createElement("a");
      const event = new MouseEvent("click");
      a.download = name || "photo";
      a.href = imgBase64;
      a.dispatchEvent(event);
    });
}

三、遇到的問題

暫無

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容