通用方法封装

2024/5/13 Vue
function base64ToBlob(urlData, type) {
  let arr = urlData.split(",");
  let array = arr[0].match(/:(.*?);/);
  let mime = (array && array.length > 1 ? array[1] : type) || type;
  // 去掉url的头,并转化为byte
  let bytes = window.atob(arr[1]);
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  // 生成视图(直接针对内存):8位无符号整数,长度1个字节
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], {
    type: mime,
  });
}
function downloadExportFile(blob, fileName) {
  let downloadElement = document.createElement("a");
  let href = blob;
  if (typeof blob == "string") {
    downloadElement.target = "_blank";
  } else {
    href = window.URL.createObjectURL(blob); //创建下载的链接
  }
  downloadElement.href = href;
  downloadElement.download = fileName; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //触发点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  if (typeof blob != "string") {
    window.URL.revokeObjectURL(href); //释放掉blob对象
  }
}
/*
下载Base64文件流形式 文件
base64 base64文件流
fileName 文件名(需带后缀 判断文件类型)
*/
export const downloadBase64File = (base64, fileName) => {
  let fileType = fileName.split(".")[fileName.split(".").length - 1];
  let typeHeader = BASE64_MAP[fileType]; // 定义base64 头部文件类型
  let converedBase64 = typeHeader + base64; // 拼接最终的base64
  let blob = base64ToBlob(converedBase64, fileType); // 转成blob对象
  downloadExportFile(blob, fileName); // 下载文件
};
const BASE64_MAP = {
  doc: "data:application/msword;base64,",
  docx: "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,",
  xls: "data:application/vnd.ms-excel;base64,",
  xlsx: "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,",
  pdf: "data:application/pdf;base64,",
  ppt: "data:application/vnd.ms-powerpoint;base64,",
  pptx: "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,",
  txt: "data:text/plain;base64,",
  png: "data:image/png;base64,",
  jpg: "data:image/jpeg;base64,",
  gif: "data:image/gif;base64,",
  svg: "data:image/svg+xml;base64,",
  ico: "data:image/x-icon;base64,",
  bmp: "data:image/bmp;base64,",
};
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
import { axios } from "./request";
export function getImageUrl(name: string) {
  return new URL(`../assets/image/${name}`, import.meta.url).href;
}
// 下载文件
export async function downloadFile(url, parameter, downloadName, type) {
  const result = await axios({
    method: "post",
    url: url,
    // params: parameter,
    data: parameter,
    responseType: "blob",
    timeout: 60000,
  });
  // const res = await judgeErrorByResponseType(result)
  const dom = document.createElement("a");
  const binaryData = [];
  binaryData.push(result);
  console.log(result);
  const downloadUrl = window.URL.createObjectURL(
    new Blob([result], { type: type })
  );
  dom.href = downloadUrl;
  dom.download = downloadName;
  dom.style.display = "none";

  document.body.appendChild(dom);
  dom.click();
  dom.parentNode.removeChild(dom);
  window.URL.revokeObjectURL(downloadUrl);
}
// 文件流转为base64
export function fileToBase64(file: any) {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader();
    reader.onload = function (event: any) {
      resolve(event.target.result);
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.readAsDataURL(file);
  });
}
// 文件 Base64 转为 Blob
export function Base64ToBlob(fileDataURL: any) {
  let arr = fileDataURL.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

// 文件  Base64 转为 File
export function Base64ToFile(fileDataURL: any, filename: any) {
  let arr = fileDataURL.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
export function formatTimeStr(timeStr: any) {
  if (!timeStr) return "";
  const year = timeStr.slice(0, 4);
  const month = timeStr.slice(4, 6);
  const day = timeStr.slice(6, 8);
  const hour = timeStr.slice(8, 10);
  const minute = timeStr.slice(10, 12);
  const second = timeStr.slice(12, 14);
  const date = `${year}-${month}-${day}`;
  const time = `${hour}${minute ? ":" + minute : ""}${
    second ? ":" + second : ""
  }`;
  return `${date} ${time}`;
}
/**
 * 字符串转utf8字节数组
 * @param {string} str
 * @returns {bytes}
 */

export function string2UTF8Bytes(str: any) {
  const bytes = new Array();
  let len, c;
  len = str.length;
  for (let i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if (c >= 0x010000 && c <= 0x10ffff) {
      bytes.push(((c >> 18) & 0x07) | 0xf0);
      bytes.push(((c >> 12) & 0x3f) | 0x80);
      bytes.push(((c >> 6) & 0x3f) | 0x80);
      bytes.push((c & 0x3f) | 0x80);
    } else if (c >= 0x000800 && c <= 0x00ffff) {
      bytes.push(((c >> 12) & 0x0f) | 0xe0);
      bytes.push(((c >> 6) & 0x3f) | 0x80);
      bytes.push((c & 0x3f) | 0x80);
    } else if (c >= 0x000080 && c <= 0x0007ff) {
      bytes.push(((c >> 6) & 0x1f) | 0xc0);
      bytes.push((c & 0x3f) | 0x80);
    } else {
      bytes.push(c & 0xff);
    }
  }
  return bytes;
}

export function UTF8Bytes2String(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12:
      case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(
          ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
        );
        break;
    }
  }

  return out;
}
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
Last Updated: 2024/5/13 13:36:32