/*href:下载的链接;downloadName:下载到本地的文件名*/
downloadFile = (href, downloadName) => {
// const oa = document.createElement('a');
// let e = document.createEvent("MouseEvents");
// e.initEvent("click", false, false); //初始化事件对象
// oa.href = href; //设置下载地址
// oa.download = ''; //设置下载文件名
// oa.target = "_blank";
// oa.dispatchEvent(e); //给指定的元素,执行事件click事件
let xhr = new XMLHttpRequest();
xhr.open("get", href, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (this.status === 200) {
const blob = new Blob([this.response], { type: this.response.type });
let url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = downloadName;
link.click();
URL.revokeObjectURL(url);
}
};
xhr.send();
};
文件直接下载( 解决图片,视频点击下载的时候在浏览器默认是打开)
最新推荐文章于 2024-09-25 16:25:48 发布
本文介绍了一种使用前端JavaScript实现文件下载的方法,通过XMLHttpRequest请求获取文件,并创建 Blob 对象及临时 URL 实现文件的下载。
1万+

被折叠的 条评论
为什么被折叠?



