简体   繁体   English

如何在 JS/React 中下载 mp4 视频?

[英]How to Download mp4 video in JS/React?

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 )我有 mp4 视频的链接(例如: 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.请帮我解决这个问题。

I solved it using following code,我使用以下代码解决了它,

let xhr = new XMLHttpRequest();
xhr.open('GET', 'path/videoLink', true);
xhr.responseType = 'blob';
xhr.onload = function () {
let urlCreator = window.URL || window.webkitURL;
let videoUrl = urlCreator.createObjectURL(this.response);
let tag = document.createElement('a');
tag.href = videoUrl;
tag.target = '_blank';
tag.download = skillName.includes('.mp4') ? skillName : skillName + '.mp4';
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
};
xhr.onerror = (err) => {};
xhr.send();
fetch('https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/mp4',
    },
  })
  .then((response) => response.blob())
  .then((blob) => {
    const url = window.URL.createObjectURL(
      new Blob([blob]),
    );
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute(
      'download',
      `FileName.pdf`,
    );
    document.body.appendChild(link);
    link.click();
    link.parentNode.removeChild(link);
  });

let me know if it worked thanks让我知道它是否有效谢谢

Such function work for me, but there's a catch:这样的 function 对我有用,但有一个问题:

with that approach ur browser will first store the video in the RAM and when the video is too big it will crash.使用这种方法,您的浏览器将首先将视频存储在 RAM 中,当视频太大时,它会崩溃。 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.我们在这里创建一个blob,因为标签下载属性需要源是你的域,当你在本地主机上测试它并且你尝试从另一个源下载它会抛出错误。

 const downloadVideo = (urls: string) => { axios({ url, method: 'GET', responseType: 'blob', }).then((response) => { const urlObject = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = urlObject; link.setAttribute('download', 'recording.mp4'); document.body.appendChild(link); link.click(); document.body.removeChild(link); }); };

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要在不创建 blob 的情况下下载视频,它需要来自你的来源或服务它的服务器需要 append Content-Disposition 和 Allow Origin 标头,然后你可以使用target="_blank"属性下载它

Efficient solution, with fetch高效的解决方案,带fetch

const handleDownloadVideo = async () => {
    try {
      const videoUrl = 'https://www.pexels.com/video/1093662/download/';
      const videoRequest = new Request(videoUrl);
      fetch(videoRequest)
        .then(() => {
          const link = document.createElement('a');
          link.href = videoUrl;
          link.setAttribute('download', 'waterfall.mp4');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
    } catch (error) {
      console.error(error);
    }
  };

Note: this answer is similar to one above , but with fetch .注意:这个答案与上面的答案类似,但带有fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM