Nas*_*ims 6 html javascript video download save-as
当您有视频的直接链接时,通常可以右键单击,然后会出现鼠标菜单。一旦到了那里你就会看到Save Video As
。如果您点击它,它将把视频下载到您的计算机上。
我想要相同的功能,但我想在 HTML 页面上创建一个按钮,当您单击该按钮时,它会执行与上面提到的完全相同的操作。
我怎样才能做到这一点?
让我们看这个例子:我有这个链接:https://invidious.fdn.fr/latest_version ?id=NF_69Dyle1Y&raw&itag=22
这是一个用于将视频保存在本地存储中的对话框。
现在我的问题是我想通过单击 html 按钮来完成这一切。我希望打开保存对话框,而不必继续播放视频并右键单击等。有没有办法做到这一点?
html a 标签的下载属性不起作用。我尝试过像这样使用 URI
<a href='"data:application/octet-stream,"+encodeURIComponent(`https://invidious.fdn.fr/latest_version?id=NF_69Dyle1Y&raw&itag=22`)' download="video.mp4">download video</a>
Run Code Online (Sandbox Code Playgroud)
但它也不起作用。
小智 8
<a href="/path/to/video.mp4" download="video">Download</a>
Run Code Online (Sandbox Code Playgroud)
相当简单,不需要 JavaScript,并且适用于除 IE 之外的所有浏览器。
在测试我的解决方案时,我发现出于安全目的, Chrome和Firefox会阻止跨源下载。
如果服务器实现了适当的 CORS,或者如果您可以控制服务器并且可以添加这些 CORS,则可以使用我无耻地从这个问题中获取的这个脚本:
<!-- The style="display:none;" is optional, you can remove it if you don't want the feature explained below. -->
<a id="download-link" href="javascript:alert('The video is not yet ready!')" download="video" style="display:none;">Download</a>
<script>
var a = document.getElementById("download-link");
function downloadResource(url, filename) {
// Current blob size limit is around 500MB for browsers
if (!filename) filename = url.split('\\').pop().split('/').pop();
fetch(url, {
headers: new Headers({
'Origin': location.origin
}),
mode: 'cors'
})
.then(response => response.blob())
.then(blob => {
let blobUrl = window.URL.createObjectURL(blob);
// Place the resource in the href of the link
a.href = blob;
// Bonus : Only show the link if and when the Javascript code has executed
a.style.display = "inline";
})
.catch(e => console.error(e));
}
downloadResource("https://invidious.fdn.fr/latest_version?id=NF_69Dyle1Y&raw&itag=22");
</script>
Run Code Online (Sandbox Code Playgroud)
我添加了一个小功能,可以在文件完全下载之前保持链接隐藏。您当然可以根据您的要求更改此设置。
如果它使用 CORS 并允许所有来源(或至少是您的来源),则上面的脚本应该可以工作。
如果没有,那么很遗憾,你运气不好。您仍然可以在新窗口中打开视频并告诉用户右键单击并手动“另存为”;它不太整洁,但至少它有效。
归档时间: |
|
查看次数: |
13431 次 |
最近记录: |