js实现浏览器下载视频

第一种,这种比较节能,如果视频比较大。不会造成卡顿

fetch('你的视频地址.mp4').then(res => res.blob()).then(blob => {
 const a = document.createElement('a');
  document.body.appendChild(a)
  a.style.display = 'none'
  const url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = '视频.mp4';
  a.click();
  document.body.removeChild(a)
  window.URL.revokeObjectURL(url);
})

第二种,此方法适合url地址中不带参数的地址,和text,wprd,pdf,等文件

demo() {
            var url = 'http://1305935074.vod2.myqcloud.com/19b93487vodcq1305935074/393c276c3701925920977239345/f0.mp4'
            var xhr = new XMLHttpRequest()
            xhr.open('get', url, true) // 也可以使用POST方式,根据接口
            xhr.responseType = 'blob' // 返回类型blob

            xhr.onload = function () {
                if (this.status === 200) {
                    var blob = this.response
                    var reader = new FileReader()

                    reader.readAsDataURL(blob) // 转换为base64,可以直接放入a表情href
                    reader.onload = function (e) {
                        var a = document.createElement('a')
                        a.download = '下载文件名' //下载文件名
                        a.href = e.target.result
                        a.click()
                        window.URL.revokeObjectURL(e.target.result)
                    }
                }
            }
            xhr.send()
        },

 

 

参考文章:https://blog.csdn.net/weixin_42981560/article/details/115507234

posted @ 2021-07-16 15:30  WongDaWEEE  阅读(1921)  评论(0编辑  收藏  举报