前端根据在线mp4 url下载视频文件(而不是浏览器直接打开视频在线播放)

发布时间 2023-07-10 10:03:08作者: 夏威夷8080

 

<!DOCTYPE html>
<html>
<head>
  <title>视频下载</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <h1>视频下载</h1>
  <button onclick="downloadVideo()">下载视频</button>

  <script>
    function downloadVideo() {
      var videoUrl = "http://111.22.3.44:80/hh00002/20230705215606-00000222-00000225-1.mp4"; // 替换为你要下载的视频的URL
      var fileName = "video.mp4"; // 下载的文件名

      // 创建一个隐藏的a标签
      var a = document.createElement('a');
      a.style.display = 'none';
      document.body.appendChild(a);

      // 使用XMLHttpRequest下载视频
      var xhr = new XMLHttpRequest();
      xhr.open('GET', videoUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function() {
        if (xhr.status === 200) {
          // 将视频Blob对象创建一个临时URL
          var videoBlob = xhr.response;
          var url = window.URL.createObjectURL(videoBlob);

          // 设置a标签的属性,并触发点击事件进行下载
          a.href = url;
          a.download = fileName;
          a.click();

          // 释放URL对象
          window.URL.revokeObjectURL(url);
        }
      };

      xhr.send();
    }
  </script>
</body>
</html>