一. a 标签完成
- <a href="文件链接" download='下载文件名'>
- </a>
- <--! 但是其中的 download 对应音频文件和视频文件无效 -->
二. JS 实现下载
- <script>
- const a = document.createElement('a');
- a.setAttribute('href', '文件链接'); //a.href='文件链接'
- a.setAttribute('download', '文件名'); //a.download='文件名'
- a.click();
- </script>
专门建立的学习 Q-q-u-n: 731771211, 分享学习方法和需要注意的小细节, 不停更新最新的教程和学习技巧
(从零基础开始到前端项目实战教程, 学习工具, 全栈开发学习路线以及规划)
三. JS 中 Ajax 实现音频或者视频不跳转进行文件下载
写代码的思路
先请求音频的链接, 再把返回值转换成二进制, 再根据他二进制对象生成新链接, 再创建 a 标签, 点击 a 标签
- // 这是 vue 里面的写的普通页面也差不多
- <script>
- this.$axios({
- method: 'get',
- url: row.src,
- responseType: 'blob' // 这个不能少, 让 response 二进制形式, 如果你按照网上教程不设置这个将返回值进行 BLOB([]) 进行处理可能会出现解析错误
- }).then(response => {
- const href = URL.createObjectURL(response.data); // 根据二进制对象创造新的链接
- const a = document.createElement('a');
- a.setAttribute('href', href);
- a.setAttribute('download', row.title);
- a.click();
- URL.revokeObjectURL(href);
- }
- </script>
四. fetch 实现
- // 原理和 Ajax 一模一样
- function request() {
- fetch('< 接口地址 >', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: '< 请求参数: json 字符串 >',
- })
- .then(res => res.blob())
- .then(data => {
- let blobUrl = Windows.URL.createObjectURL(data);
- download(blobUrl);
- });
- }
- function download(blobUrl) {
- const a = document.createElement('a');
- a.download = '< 文件名 >';
- a.href = blobUrl;
- a.click();
- }
- request();
专门建立的学习 Q-q-u-n: 731771211, 分享学习方法和需要注意的小细节, 不停更新最新的教程和学习技巧
(从零基础开始到前端项目实战教程, 学习工具, 全栈开发学习路线以及规划)
来源: http://www.jianshu.com/p/248c465c1040