vue3+ts 前端word文档下载文件时不预览直接下载方法(支持 doc / excel / ppt / pdf 等)

前端word文档下载文件时不预览直接下载方法支持 doc / excel / ppt / pdf 等

根据需要,要实现一个下载文档的需要

最简单的方法就是使用a标签

如果是相同域可以直接下载,但如果是不同域的,就会先打开一个预览页,在预览页再点下载。

但其实我希望得到的效果是,当我点击下载时,可以直接下载,不要预览,可以使用如下方法



代码如下:

复制代码
	const downloadRecordHandler = (url) => {
		console.log("url", url);
		let filename = "xxxxxxx"; //文件名
		getBlob(url).then((blob) => {
			saveAs(blob, filename);
		});
	};

	const getBlob = (url) => {
		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();
		});
	};
	const saveAs = (blob, filename) => {
		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);
		}
	};

这样就实现了我想要的效果。

相关推荐
前端双越老师14 小时前
程序员 1v1 访谈系列第十三期:大龄已育空窗一年如何破局
前端·ai编程·全栈
恋猫de小郭14 小时前
Flutter 大小核优化又被回滚,然后又开新提案?
android·前端·flutter
MyBili14 小时前
Chrome扩展开发入门:从零打造实用浏览器插件
前端·chrome·谷歌浏览器·效率工具·浏览器插件·前端入门·扩展开发
FungLeo14 小时前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
风骏时光牛马15 小时前
AI_Coding:智能代码创作引擎
前端
FungLeo15 小时前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
卸任1 天前
Vibe coding工具使用心得
前端·ai编程
brien91 天前
为什么模型标称 1M,Google Antigravity 聊到 256K 却突然失忆?我们给它做了个原生行内监控圆环
前端
修炼的dance1 天前
录屏关键帧间隔多少合适?六档实测,2秒到10秒小了75.6%
前端