vue下载各类型文件

108 阅读1分钟

工具包downloadFile.js

import axios from 'axios'
export const downloadFile = (url, filename) =>
  axios
    .get(url, {
      responseType: 'blob',
    })
    .then((res) => {
      let fileType = "";
      if (url.lastIndexOf(".") > -1) {
        let fileExtension = url
          .slice(url.lastIndexOf(".") + 1)
          .toLowerCase();
        switch (fileExtension) {
          case "pdf":
            fileType = "application/pdf";
            break;
          case "doc":
            fileType = "application/msword";
            break;
          case "docx":
            fileType =
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            break;
          case "xls":
            fileType = "application/vnd.ms-excel";
            break;
          case "xlsx":
            fileType =
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            break;
          case "png":
            fileType = "image/png";
            break;
          case "jpg":
            fileType = "image/jpeg";
            break;
          case "jpeg":
            fileType = "image/jpeg";
            break;
          case "mp3":
            fileType = "audio/mpeg";
            break;
          case "mp4":
            fileType = "video/mpeg";
            break;
          case "lrc":
            fileType = "lrc";
            break;
          case "ppt":
            fileType = "application/vnd.ms-powerpoint";
            break;
          case "pptx":
            fileType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            break;
          case "txt":
            fileType = "text/plain";
            break;
        }
      }
      const blob = new Blob([res], { type: fileType }) // 构造一个blob对象来处理数据,并设置文件类型
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10
        navigator.msSaveBlob(blob, filename)
      } else {
        const href = URL.createObjectURL(blob) // 创建新的URL表示指定的blob对象
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = href // 指定下载链接
        a.download = filename // 指定下载文件名
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL对象
      }
    })