如何在JS/React下载MP4视频?
这可能是很早就被问到的,但是我无法弄清楚,请帮助我,并提前感谢。
问题:
我有一个链接到mp4视频(ex: https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4 )
我想从前端下载此视频。
我已经尝试了以下方法:
const videoHref ='https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4';
const a = Object.assign(document.createElement('a'), {
href: videoHref,
style: 'display: none',
download: 'video.mp4'
});
document.body.appendChild(a);
a.click();
a.remove();
但是当我执行此代码时,
下载将立即开始并失败,错误
失败 - 没有文件
请帮助我解决此问题。
This might have been asked early, but I am unable to figure it out, please help me and thanks in advance.
Problem:
I have a link to mp4 video (ex: https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4)
I want to download this video from front end.
I have tried the following method:
const videoHref ='https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4';
const a = Object.assign(document.createElement('a'), {
href: videoHref,
style: 'display: none',
download: 'video.mp4'
});
document.body.appendChild(a);
a.click();
a.remove();
But when I execute this code,
the download will start and fails immediately with error
Failed - No file
Please help me resolve this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我使用以下代码解决了它,
I solved it using following code,
高效的解决方案,带有 fetch
注意:这个答案类似于上面的一个,但带有
fetch
。Efficient solution, with fetch
Note: this answer is similar to one above, but with
fetch
.将其添加到您的服务器端
单击按钮即可将此代码添加到您的客户端应用程序中。
Add this into your server side
Add add this code into your client side application on the click of your button.
让我知道它是否有效
谢谢
let me know if it worked
thanks
这样的功能对我有用,但有一个问题:
使用这种方法,你的浏览器将首先将视频存储在 RAM 中,当视频太大时,它会崩溃。我们在这里创建一个 blob,因为 a 标签下载属性需要源是您的域,当您在本地主机上测试它并尝试从另一个源下载时,它会抛出错误。
要下载视频而不创建 blob,它需要来自您的源,或者提供它的服务器需要附加 Content-Disposition 和允许源标头,然后您可以使用 a 和 target 来下载它="_blank" 属性
Such function work for me, but there's a catch:
with that approach ur browser will first store the video in the RAM and when the video is too big it will crash. We're creating a blob here, because a tag download attribute needs the origin to be ur domain, when u test it on localhost and you try to download from another origin it would throw an error.
To download video without creating a blob it needs to be from ur origin or the server serving it needs to append Content-Disposition and Allow Origin headers, then u can just download it with a with target="_blank" property