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