强制从 JavaScript 浏览器中的 URL(客户端站点)下载 YouTube 视频



我正在开发使用基于node的服务器站点的YouTube视频下载器站点。我正在使用npm名为 ytdl-core 的软件包,此模块返回下载链接。但是,当我单击该链接时,它会将我重定向到"视频预览"而不是"触发下载",

ytdl(url, function(err, format) {
  if (err) {res.send('the url is invalid please try again...');}
  console.log((format.formats).length);//i am getting value... in console but not outside of the function.. 
  //this object contains all the download links  
  var links = []
  for( var i= 0, len = (format.formats).length; i < len; i++) {
    var el = format.formats[i].container;
    if ( el === 'mp4') {
      var download_url = format.formats[i];
      //this push will store the all links in 'links' object..
      links.push(download_url);
    }
  }
  console.log(links);
});

因此,当我将链接粘贴到浏览器中时,它会将我重定向到预览而不是触发下载。我得到的链接如下所示:

https://r8---sn-gxap5ojx-cage.googlevideo.com/videoplayback?upn=P6gEaXLtqOc&ei=ROrcWMzGKsjfoAPtl6XYAg&id=o-AIBZRxwo9AvJU4q02_xR0lfxJbSV3pxpga67Si4bLieu&key=yt6&ip=139.59.64.12&ipbits=0&pl=20&requiressl=yes&initcwndbps=8882500&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&itag=18&expire=1490894500&mime=video%2Fmp4&pcm2cms=yes&source=youtube&mv=m&mt=1490872775&ms=au&lmt=1487309879666192&clen=8449602&gir=yes&mn=sn-gxap5ojx-cage&mm=31&dur=221.518&signature=6ED71F39CAA3B6719A8BAAEABD51D568ABF4D7A3.B3EED034140574BAC9733EC5CC28EF4AC9E3F758&title=Kygo Selena Gomez It Ain t Me with Selena Gomez Audio

我的问题是,如何通过单击按钮强制将该视频下载到客户的浏览器?

如果您使用的是 express,使用 res.download(( 可能会有所帮助。它将按照这个思路工作。

res.download(downloadLink, downloadTitle, function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});

祝你好运!希望这有帮助!

我发现非常简单的解决方案是您需要将属性"download='true'添加到您的HTML代码中! 它看起来像这样

<a href='yourdownloadlink.com/example' download='true'>force download!</a>

最新更新