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);
		}
	};

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

相关推荐
EXI-小洲6 分钟前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
wangruofeng14 分钟前
Phosphor Icons 官网源码拆解:URL 即存储、水波动画与 7362 Star 图标库的架构实践
前端·架构·github
BigTopOne33 分钟前
WebRTC Native / Android 开发学习资源整理
前端
excel2 小时前
nuxt 3 升级 nuxt 4 报错之 hasInjectionContext
前端
何以解忧,唯有..2 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
软件聚导航3 小时前
「聚小软 AI 助手」技术升级:从数据库检索到 RAG 知识库问答
前端·数据库·mysql·微信小程序·小程序·ai编程·rag
恋猫de小郭3 小时前
看懂大模型架构术语,帮助你理解目前常见的大模型开源架构
前端·人工智能·ai编程
yma163 小时前
通过提示词实现GitHub Pages 和 Nginx 双部署竟然这么简单?
前端
前端 贾公子3 小时前
第09章:上下文与记忆 (2)
java·服务器·前端
可乐鸡翅yeah_3 小时前
第三方接口对接 M3U8 流媒体排坑实战,解决外部服务商流兼容难题
前端·javascript·python·django·html·m3u8·m3u8在线