唐耀东
2022-10-12 901be26b0491501afe8eb145392a8d8c307f0138
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import axios from 'axios'
import fa from 'element-ui/src/locale/lang/fa'
/**
 * 下载附件
 */
export function downFile(url, fileName) {
  let type = fileType(url);
  console.log(type);
  axios({
    url: url, // 服务器上pdf路径
    method: 'get',
    responseType: 'blob'
  }).then(res => {
    //console.log(res)
    let blob = new Blob([res.data], {
      //type类型后端返回来的数据中会有,根据自己实际进行修改
      // 表格下载为 application/xlsx,压缩包为 application/zip等,
 
      type: fileType(url),
    });
    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      var blobURL = window.URL.createObjectURL(blob);
      // 创建隐藏<a>标签进行下载
      var tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute("download", fileName);
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      window.URL.revokeObjectURL(blobURL);
    }
  }).catch(err => {
    //loading.close();
    // eslint-disable-next-line no-undef
    console.log(err)
  })
}
export function fileType(url) {
  let suffix = url.substring(url.lastIndexOf('.')+1)
  let type;
  switch (suffix) {
    case "pdf":
      type = "application/pdf";
      break;
    case "doc":
      type = "application/msword";
      break;
    case "docx":
      type = "application/msword";
      break;
    case "xls":
      type = "application/vnd.ms-excel";
      break;
    case "xlsx":
      type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      break;
    case "ppt":
      type = "application/vnd.ms-powerpoint";
      break;
    case "pptx":
      type = "application/vnd.ms-powerpoint";
      break;
    default:
      type = "";
      break;
  }
  return type;
}