目录
- 一、通过url下载文件并修改文件名称
- 二、文件流下载方式
一、通过url下载文件并修改文件名称
1.封装downloadFile.ts
export const downloadInvoke = (url: string, fileName: string) => {getBlob(url).then((blob) => {saveAs(blob, fileName);});
}export const getBlob = (url: string) => {return new Promise((resolve) => {const xhr = new XMLHttpRequest();xhr.open("GET", url, true);xhr.responseType = "blob";xhr.onload = () => {if (xhr.status === 200) {resolve(xhr.response);}};xhr.send();});
};export const saveAs = (blob: any, filename: string) => {if (window.navigator.msSaveOrOpenBlob) {navigator.msSaveBlob(blob, filename); } else {const link = document.createElement("a");const body = document.querySelector("body");link.href = window.URL.createObjectURL(blob);link.download = filename;link.style.display = "none";body.appendChild(link);link.click();body.removeChild(link);window.URL.revokeObjectURL(link.href);}
};
2.引入
import { downloadInvoke } from "@/utils/index";downloadInvoke(url, "文件名")
二、文件流下载方式
1.封装downloadFile.ts
export const downData = (res: any, fileName: string) => {if (!res) {return}if (res.type == "application/json") {const reader = new FileReader();reader.readAsText(res, "utf-8");reader.onload = function () {const msg = JSON.parse(reader.result as string);ElMessage.error(msg);}return}let url = window.URL.createObjectURL(new Blob([res]))let link = document.createElement('a')link.style.display = 'none'link.href = urllink.setAttribute('download', fileName)document.body.appendChild(link)link.click()document.body.removeChild(link)window.URL.revokeObjectURL(url)
}
2.引入
import { downData } from "@/utils/index";downData(res, "文件名.xls")