/*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-06-27 08:49:44 发布