|
@@ -0,0 +1,70 @@
|
|
|
+import { objTypeOf, blobToText } from "./utils";
|
|
|
+
|
|
|
+function parseDownloadFilename(dispositionInfo) {
|
|
|
+ const strs = dispositionInfo.split(";");
|
|
|
+ let filename = "";
|
|
|
+ strs
|
|
|
+ .map((item) => item.split("="))
|
|
|
+ .find((item) => {
|
|
|
+ if (item[0].indexOf("filename") !== -1) {
|
|
|
+ filename = decodeURI(item[1]);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ return filename;
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 通过api下载文件
|
|
|
+ * @param {AxiosPromise} fetchFunc 下载接口
|
|
|
+ * @param {String}} fileName 文件名
|
|
|
+ * @returns Promise<Boolean>
|
|
|
+ */
|
|
|
+export async function downloadByApi(fetchFunc, fileName) {
|
|
|
+ let errorInfo = null;
|
|
|
+ const res = await fetchFunc().catch((e) => {
|
|
|
+ errorInfo = e;
|
|
|
+ });
|
|
|
+
|
|
|
+ // 展示后台错误信息
|
|
|
+ if (errorInfo && objTypeOf(errorInfo) === "blob") {
|
|
|
+ const res = await blobToText(errorInfo).catch(() => {});
|
|
|
+ if (!res) return Promise.reject("下载失败!");
|
|
|
+ const resJson = JSON.parse(res);
|
|
|
+ return Promise.reject(resJson.message);
|
|
|
+ }
|
|
|
+
|
|
|
+ const filename =
|
|
|
+ fileName || parseDownloadFilename(res.headers["content-disposition"]);
|
|
|
+ downloadByBlob(new Blob([res.data]), filename);
|
|
|
+ return true;
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 下载blob
|
|
|
+ * @param {Blob} data blob对象
|
|
|
+ * @param {String} filename 文件名
|
|
|
+ */
|
|
|
+export function downloadByBlob(data, filename) {
|
|
|
+ const blobUrl = URL.createObjectURL(data);
|
|
|
+ downloadByUrl(blobUrl, filename);
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 下载url
|
|
|
+ * @param {String} url 文件下载地址
|
|
|
+ * @param {String}} filename 文件名
|
|
|
+ */
|
|
|
+export function downloadByUrl(url, filename) {
|
|
|
+ const tempLink = document.createElement("a");
|
|
|
+ tempLink.style.display = "none";
|
|
|
+ tempLink.href = url;
|
|
|
+ const fileName = filename || url.split("/").pop().split("?")[0];
|
|
|
+ tempLink.setAttribute("download", fileName);
|
|
|
+ if (tempLink.download === "undefined") {
|
|
|
+ tempLink.setAttribute("target", "_blank");
|
|
|
+ }
|
|
|
+ document.body.appendChild(tempLink);
|
|
|
+ tempLink.click();
|
|
|
+ document.body.removeChild(tempLink);
|
|
|
+ window.URL.revokeObjectURL(url);
|
|
|
+}
|