Переглянути джерело

:zap: 增加下载工具类

smallchill 5 роки тому
батько
коміт
ce14a8e065
1 змінених файлів з 57 додано та 0 видалено
  1. 57 0
      src/util/util.js

+ 57 - 0
src/util/util.js

@@ -308,3 +308,60 @@ export const getQueryString = (name) => {
   if (r != null) return unescape(decodeURI(r[2]));
   return null;
 }
+
+/**
+ * 下载文件
+ * @param {String} path - 文件地址
+ * @param {String} name - 文件名,eg: test.png
+ */
+export const downloadFileBlob = (path, name) => {
+  const xhr = new XMLHttpRequest();
+  xhr.open('get', path);
+  xhr.responseType = 'blob';
+  xhr.send();
+  xhr.onload = function () {
+    if (this.status === 200 || this.status === 304) {
+      // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
+      if ('msSaveOrOpenBlob' in navigator) {
+        navigator.msSaveOrOpenBlob(this.response, name);
+        return;
+      }
+      const url = URL.createObjectURL(this.response);
+      const a = document.createElement('a');
+      a.style.display = 'none';
+      a.href = url;
+      a.download = name;
+      document.body.appendChild(a);
+      a.click();
+      document.body.removeChild(a);
+      URL.revokeObjectURL(url);
+    }
+  };
+}
+
+/**
+ * 下载文件
+ * @param {String} path - 文件地址
+ * @param {String} name - 文件名,eg: test.png
+ */
+export const downloadFileBase64 = (path, name) => {
+  const xhr = new XMLHttpRequest();
+  xhr.open('get', path);
+  xhr.responseType = 'blob';
+  xhr.send();
+  xhr.onload = function () {
+    if (this.status === 200 || this.status === 304) {
+      const fileReader = new FileReader();
+      fileReader.readAsDataURL(this.response);
+      fileReader.onload = function () {
+        const a = document.createElement('a');
+        a.style.display = 'none';
+        a.href = this.result;
+        a.download = name;
+        document.body.appendChild(a);
+        a.click();
+        document.body.removeChild(a);
+      };
+    }
+  };
+}