后台返回 文件地址 直接下载到本地不打开新窗口

handleDownload = (url,filename) => {
	const x = new window.XMLHttpRequest();
	x.open('GET', url, true);
	x.responseType = 'blob';
	x.onload = () => {
		let time = new Date().toLocaleDateString();
		const url = window.URL.createObjectURL(x.response);
		const a = document.createElement('a');
		a.href = url;
		a.download = filename + "_" + time + '.txt';
		a.click();
	};
	x.send();
}

  使用href 的下载地址 和 当前网站地址 必须是 同源的,否则download不生效。如果不同源,使用解决方法二下载即可。

  本文参考文章:

    https://blog.csdn.net/u013919153/article/details/117279134

posted @ 2023-01-04 09:52  仙乄  阅读(35)  评论(0编辑  收藏  举报