JavaScript 下载文件
最编程
2024-07-17 14:59:38
...
ajax 下载文件
let xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.xxx.com/bbb.zip', true); // 这部至关重要,命令xhr返回给你的时blob(二进制大对象)类型的数据 xhr.responseType = 'blob'; xhr.send() xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const aTag = document.createElement('a') aTag.href = URL.createObjectURL(this.response) aTag.download = 'aaa.zip' aTag.click() } }
使用<a>标签点击下载
<a href="../../static/xxx.xlsx" download="xxx.xlsx">下载</a>
直接点击可以下载,需要注意的是download属性,当不加download属性时,如果文件格式为txt、pdf、jpg等浏览器支持直接打开的文件格式,那么不会下载,而是浏览器直接打开;添加download属性之后,就会下载,并且下载文件默认命名为你download属性的值。
使用window.open()
window.open("../../static/xxx.xlsx");// 下载本地文件 window.open("https://mp.****.net/postedit/static/xxx.xlsx");// 下载网络文件
注:中文名未测试
fetch 下载文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button onclick="download()">下载</button> <script> function downloadMp3(filePath) { fetch(filePath).then(res => res.blob()).then(blob => { const a = document.createElement('a'); document.body.appendChild(a) a.style.display = 'none' const url = window.URL.createObjectURL(blob); a.href = url; a.download = 'xxxx.mp3'; a.click(); document.body.removeChild(a) window.URL.revokeObjectURL(url); }); } function download() { this.downloadMp3('http://m10.music.com/708b9cbb995e5dfb5b27295c1.m4a'); } </script> </body> </html>
Blob下载文件
<a id="h">点此进行下载</a> <!-- js部分 ,此方法未测试--> <script> var blob = new Blob(["Hello World"]); var url = window.URL.createObjectURL(blob); var a = document.getElementById("h"); a.download = "helloworld.txt"; a.href = url; </script>
我们可以通过window.URL.createObjectURL,接收一个Blob(File)对象,将其转化为Blob URL,然后赋给 a.download属性,然后在页面上点击这个链接就可以实现下载了。
备注:download属性不兼容IE, 对IE可通过window.navigator.msSaveBlob方法或其他进行优化(IE10/11)
上一篇: vue 下载数据流文件
推荐阅读
-
C# 文件操作
-
Idea-Maven 的设置文件 Disk Configuration-2.Setting.xml
-
Linux 和 Windows 为文件共享创建共享文件夹
-
Django 管理后台无法加载 css 文件
-
Oracle 查询数据库占用大小 - 查询所有文件占用大小
-
Linux] 内存文件系统 I/O、重定向内存文件系统 I/O、重定向
-
node.js 下载和安装以及环境配置超级详细教程 [Windows 版本]。
-
[Linux] 逐层了解文件系统 - (3) 存储文件的磁盘组织结构
-
msvcr100.dll 丢失解决方案,如何安全下载 msvcr100.dll 文件:完整指南
-
(文件