js如何通过链接下载一个视频(备忘)

downloadFile(fileurl, filename) {
				let _that = this;
				this.$http.defaults.timeout = 100 * 60 * 1000;
//fileurl 为视频地址
				this.$http.get(
					fileurl, {
						responseType: 'blob',
						onDownloadProgress(progress) {
							//_that.downProgress = Math.round(progress.loaded / progress.total * 100) + '%'
						}
					}
				).then(response => {
					let blob = response;
					if (typeof window.navigator.msSaveBlob !== 'undefined') {
						window.navigator.msSaveBlob(blob, filename)
					} else {
						let URL = window.URL || window.webkitURL;
						// 使用获取到的blob对象创建的blobUrl
						const blobUrl = URL.createObjectURL(blob);

						const a = document.createElement('a');

						if (typeof a.download === 'undefined') {
							window.location = blobUrl
						} else {
							document.body.appendChild(a)
							a.style.display = 'none'
							a.href = blobUrl;
							// 指定下载的文件名
							a.download = filename;
							a.click();
							document.body.removeChild(a)
							// 移除blob对象的blobUrl
							URL.revokeObjectURL(blobUrl);
						}
					}
					this.downloading = false;
				}).catch((error) => {
					//throw error;
					//this.$message({
					//	showClose: true,
					//	message: '下载失败,请重试..',
					//	type: 'error'
					//});
					//this.downloading = false;
				})
			},

this.$http为通过axios封装的函数  

坑为有跨域问题,需后端配合解决跨域

公司使用jq+vue的项目,所以还得来个jq的,代码半路接手,鬼知道前面人给设置了什么,jq的设置restype不起作用,无奈使用原生写法

	var xhr = new XMLHttpRequest()
	xhr.onreadystatechange = function () {
	    if (this.readyState == 4 && this.status == 200) {
	        // handler(this.response)
	        console.log(this.response, typeof this.response)
	        let blob = this.response;
	        		if (typeof window.navigator.msSaveBlob !== 'undefined') {
	        			window.navigator.msSaveBlob(blob, '下载文件.mp4')
	        		} else {
	        			let URL = window.URL || window.webkitURL;
	        			// 使用获取到的blob对象创建的blobUrl
	        			const blobUrl = URL.createObjectURL(blob);
	        		
	        			const a = document.createElement('a');
	        		
	        			if (typeof a.download === 'undefined') {
	        				window.location = blobUrl
	        			} else {
	        				document.body.appendChild(a)
	        				a.style.display = 'none'
	        				a.href = blobUrl;
	        				// 指定下载的文件名
	        				a.download = '下载文件.mp4';
	        				a.click();
	        				document.body.removeChild(a)
	        				// 移除blob对象的blobUrl
	        				URL.revokeObjectURL(blobUrl);
	        			}
	        		}
	    }
	}
	xhr.open('GET',url)
	xhr.responseType = 'blob'
	xhr.send()

这个也不用注释了...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值