我正在使用以下方法实现 YouTube 视频下载器ytdl核心 https://www.npmjs.com/package/ytdl-core带有 Nodejs 后端和 Reactjs 前端。但是,使用 ytdl-core 库,我可以使用此代码块将视频文件发送到前端
app.get('/download', (req, res) => {
let { url, itag } = req.query;
let id = ytdl.getURLVideoID(url);
ytdl.getInfo(id, (err, info) => {
if (err) {
console.log(err);
throw err;
}
else{
let audioandvideo = ytdl.filterFormats(info.formats, 'audioandvideo');
let video = audioandvideo.filter(obj => obj.itag === itag);
video = video[0]
res.header('Content-Disposition', `attachment; filename="${info.title}.${video.container}"`);
res.header('Content-Type', 'video/webm');
ytdl(url, {
format: video
}).pipe(res);
}
})
});
但是,如果我将网页重定向到这样的路线,文件就会正确下载
window.location.href = `http://localhost:5000/download?url=${this.state.url}&itag=${itag}`;
这工作正常并且视频下载正确。但由于它是重定向,我无法在托管站点中执行此操作。所以,我需要使用 axios 来做到这一点。
我做了一些研究并找到了一些解决方案。我尝试过js 文件下载 https://www.npmjs.com/package/js-file-download图书馆遵循接受的答案here https://stackoverflow.com/questions/41938718/how-to-download-files-using-axios。它将文件下载到客户端目录,但文件无法播放。这是我使用的代码块
downloadVideo(itag){
axios.get(`http://localhost:5000/download`, {
params: { url: this.state.url, itag },
})
.then(response => {
fileDownload(response.data, `video.mp4`);
})
.catch(err => console.log(err));
}
由于它不起作用,我也尝试了前面提到的 StackOverflow 答案中提到的另一种方法。它还会下载文件,但效果不佳。
我怎样才能解决这个问题?我的 axios 请求无法正常工作的原因可能是什么?
EDIT :
downloadVideo(itag){
axios.get(`http://localhost:5000/download`, {
params: { url: this.state.url, itag },
responseType: Blob
})
.then(response => {
fileDownload(response.data, `video.mp4`);
})
.catch(err => console.log(err));
// window.location.href = `http://localhost:5000/download?url=${this.state.url}&itag=${itag}`;
}
这是前端代码。如果我使用注释的代码块(window.location.href
) 代替axios.get
文件被下载并且可以工作。但如果我使用axios.get
下载了一个文件,但它似乎是一个损坏的文件,因为它没有播放。