使用reactjs进行文件下载无法正常工作(使用axios)

时间:2019-05-25 15:05:12

标签: javascript reactjs download axios youtube-dl

我正在使用ytdl-core和Node.js后端和Reactjs前端来实现youtube视频下载器。但是,使用ytdl-core库,我可以使用此代码块将视频发送到youtube视频文件进行前端

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-file-downloadhere库中进行了尝试。它将文件下载到客户端目录,但该文件无法播放。这是我用于此的代码块

  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请求无法正常工作的原因可能是什么?

编辑

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,则会下载一个文件,但由于它无法播放,因此似乎是损坏的文件。

0 个答案:

没有答案
相关问题