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

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

相关推荐
anOnion7 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户47949283569157 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
zhangxingchao9 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒11 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic12 小时前
SwiftUI 手势笔记
前端·后端
橙子家13 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user205855615181313 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州13 小时前
CSS aspect-ratio 属性完全指南
前端
Pedantic15 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端