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

jq6vz3qz  于 2022-11-29  发布在  React
关注(0)|答案(4)|浏览(326)

这可能是早就问过了,但我无法弄清楚,请帮助我,并提前感谢。
问题:
我有指向mp4视频的链接(例如:(第10页)
我想从前端下载此视频。
我试过以下方法:

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();

但当我执行这段代码时,
下载将开始并立即失败,并显示错误
失败-无文件
请帮我解决这个问题。

igsr9ssn

igsr9ssn1#

我用下面代码解决了这个问题:

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();
zf9nrax1

zf9nrax12#

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);
  });

让我知道如果它的工作谢谢

pxq42qpu

pxq42qpu3#

这样的功能对我来说很有效,但有一个问题:
我们在这里创建了一个blob,因为a标签下载属性需要源地址是我们的域,当你在本地主机上测试它,并且你试图从另一个源地址下载时,它会抛出一个错误。

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);
  });
};

要下载视频而不创建blob,它需要来自您的源或服务器需要附加Content-Disposition和Allow Origin头,然后您可以使用awith target="_blank” property下载它

moiiocjp

moiiocjp4#

高效的解决方案,具有提取功能

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);
    }
  };

注意:此答案类似于one above,但使用了fetch

相关问题