下载视频,支持跨域。
- url:视频地址
- name:自定义下载文件名字
1、a标签通过转换后的url下载文件(视频不会跳转)
- axio 类同,但是需要下载依赖,fetch是windows下自带的,更方便
- 有个缺点:http网页不能下载https的视频、https不能下载http。已在代码处理截掉头部处理
// 测试视频
const video_url = 'https://media.w3.org/2010/05/sintel/trailer.mp4';
// 下载函数
function daonload(url, name){
// 去掉头部,解决http和https之间,网页和资源不同禁止下载问题
const getUrl = url.replace(/http:|https:/, '');
fetch(getUrl )
.then(res => res.blob())
.then(blob => {
// 获取名字(当未传递name时使用),根据实际情况,如果有? 后缀参数根据自行截取
const urlSplitArr = getUrl.split('/');
const a = document.createElement("a");
const objectUrl = window.URL.createObjectURL(blob);
a.download = name || urlSplitArr[urlSplitArr.length - 1];
a.href = objectUrl;
a.click();
window.URL.revokeObjectURL(objectUrl);
a.remove();
})
}
// 调用下载
download(video_url, ('test_video'+Date.now()))
2、iframe标签实现下载文件
// 测试视频
const url = 'https://media.w3.org/2010/05/sintel/trailer.mp4';
// 下载函数
function download(url){
const iframe = document.createElement("iframe");
iframe.setAttribute("hidden","hidden");
document.body.appendChild(iframe);
iframe.onload = () => {
if(iframe){
iframe.setAttribute('src','about:blank');
}
};
iframe.setAttribute("src",url);
}
// 调用下载
download(url)
其他方案一般般,也有用插件的,暂时就这两个实用一些。
注意,此方案曾遇跨域风险
转载自:https://blog.csdn.net/yun_master/article/details/114551493