uniapp 开发H5视频下载

调用download.js下载

在页面目录下新建download.js文件,使用的时候引入。
在这里插入图片描述
download.js


(function (root, factory) {
    
    
	if (typeof define === 'function' && define.amd) {
    
    
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if (typeof exports === 'object') {
    
    
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = factory();
	} else {
    
    
		// Browser globals (root is window)
		root.download = factory();
  }
}(this, function () {
    
    

	return function download(data, strFileName, strMimeType) {
    
    

		var self = window, // this script is only for browsers anyway...
			defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
			mimeType = strMimeType || defaultMime,
			payload = data,
			url = !strFileName && !strMimeType && payload,
			anchor = document.createElement("a"),
			toString = function(a){
    
    return String(a);},
			myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
			fileName = strFileName || "download",
			blob,
			reader;
			myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
	  
		if(String(this)==="true"){
    
     //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
			payload=[payload, mimeType];
			mimeType=payload[0];
			payload=payload[1];
		}


		if(url && url.length< 2048){
    
     // if no filename and no mime, assume a url was passed as the only argument
			fileName = url.split("/").pop().split("?")[0];
			anchor.href = url; // assign href prop to temp anchor
		  	if(anchor.href.indexOf(url) !== -1){
    
     // if the browser determines that it's a potentially valid url path:
        		var ajax=new XMLHttpRequest();
        		ajax.open( "GET", url, true);
        		ajax.responseType = 'blob';
        		ajax.onload= function(e){
    
     
				  download(e.target.response, fileName, defaultMime);
				};
        		setTimeout(function(){
    
     ajax.send();}, 0); // allows setting custom ajax headers using the return:
			    return ajax;
			} // end if valid url?
		} // end if url?


		//go ahead and download dataURLs right away
		if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
    
    
		
			if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
    
    
				payload=dataUrlToBlob(payload);
				mimeType=payload.type || defaultMime;
			}else{
    
    			
				return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
					navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
					saver(payload) ; // everyone else can save dataURLs un-processed
			}
			
		}//end if dataURL passed?

		blob = payload instanceof myBlob ?
			payload :
			new myBlob([payload], {
    
    type: mimeType}) ;


		function dataUrlToBlob(strUrl) {
    
    
			var parts= strUrl.split(/[:;,]/),
			type= parts[1],
			decoder= parts[2] == "base64" ? atob : decodeURIComponent,
			binData= decoder( parts.pop() ),
			mx= binData.length,
			i= 0,
			uiArr= new Uint8Array(mx);

			for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);

			return new myBlob([uiArr], {
    
    type: type});
		 }

		function saver(url, winMode){
    
    

			if ('download' in anchor) {
    
     //html5 A[download]
				anchor.href = url;
				anchor.setAttribute("download", fileName);
				anchor.className = "download-js-link";
				anchor.innerHTML = "downloading...";
				anchor.style.display = "none";
				document.body.appendChild(anchor);
				setTimeout(function() {
    
    
					anchor.click();
					document.body.removeChild(anchor);
					if(winMode===true){
    
    setTimeout(function(){
    
     self.URL.revokeObjectURL(anchor.href);}, 250 );}
				}, 66);
				return true;
			}

			// handle non-a[download] safari as best we can:
			if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
    
    
				url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
				if(!window.open(url)){
    
     // popup blocked, offer direct download:
					if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){
    
     location.href=url; }
				}
				return true;
			}

			//do iframe dataURL download (old ch+FF):
			var f = document.createElement("iframe");
			document.body.appendChild(f);

			if(!winMode){
    
     // force a mime that will download:
				url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
			}
			f.src=url;
			setTimeout(function(){
    
     document.body.removeChild(f); }, 333);

		}//end saver




		if (navigator.msSaveBlob) {
    
     // IE10+ : (has Blob, but not a[download] or URL)
			return navigator.msSaveBlob(blob, fileName);
		}

		if(self.URL){
    
     // simple fast and modern way using Blob and URL:
			saver(self.URL.createObjectURL(blob), true);
		}else{
    
    
			// handle non-Blob()+non-URL browsers:
			if(typeof blob === "string" || blob.constructor===toString ){
    
    
				try{
    
    
					return saver( "data:" +  mimeType   + ";base64,"  +  self.btoa(blob)  );
				}catch(y){
    
    
					return saver( "data:" +  mimeType   + "," + encodeURIComponent(blob)  );
				}
			}

			// Blob but not URL support:
			reader=new FileReader();
			reader.onload=function(e){
    
    
				saver(this.result);
			};
			reader.readAsDataURL(blob);
		}
		return true;
	}; /* end download() */
}));

项目完整代码

<template>
	<view class="content">
		<image class="bg-set" src="/static/bj.png" :style=" {height:windowHeight +'px'} "> </image>
		<image class="btn-set" src="/static/xz.png" @click="clickDownLoad"> </image>		
		<view class="videoPoster" v-if="showVideo">
			<video
				src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-a450e3eb-029c-4568-83af-cd4160c8852e/c14e12c5-5542-4031-a414-6e70094b8829.mp4"
				autoplay="autoplay" >				
			</video>
		</view>
		
	</view>
</template>

<script>	
	export default {
    
    
		data() {
    
    
			return {
    
    
				windowWidth: 0,
				windowHeight: 0,
				showVideo: true
			}
		},

		onLoad() {
    
    			
			uni.getSystemInfo({
    
    
				success: (res) => {
    
    
					//console.log(res)
					this.windowWidth = res.windowWidth
					this.windowHeight = res.windowHeight
				}
			});
		},

		methods: {
    
    
			clickDownLoad() {
    
    
				console.log('下载');	
				
				// ***判断是否在微信内打开,如果是,提示用户在外部浏览器打开,否则运行下载代码***
				var ua = navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
    
    
					alert("请在右上角...点击【在浏览器打开】")
				} else {
    
    					
					this.downLoad()  //调用下载函数
					this.showVideo = false
				    uni.showLoading({
    
    				    					    			
				       title: "正在下载"				    
				    });
				}
			},
			
			downLoad() {
    
    			
				//测试发现,在pc端正常下载; 在移动端 qq浏览器,safari浏览器不能下载	
				let that = this;
				let url =' https://vkceyugu.cdn.bspapp.com/VKCEYUGU-a450e3eb-029c-4568-83af-cd4160c8852e/c14e12c5-5542-4031-a414-6e70094b8829.mp4 ';
				
				//**调用download.js下载,下载速度相对快一些**
				let downjs = require("./download.js"); //引用当前目录下的自定义函数
				let x=new XMLHttpRequest();
				x.open("GET", url, true);
				x.responseType = 'blob';
				x.onload=function(e) {
    
    
					downjs(x.response, "9898.mp4", "video/mp4" )
					uni.hideLoading()
					that.showVideo = true
				};
				x.send();
				
				
				//**不调用download.js下载**
				// let xhr = new XMLHttpRequest();
				// xhr.open('GET', url, true);
				// xhr.responseType = 'blob'; // 返回类型blob
				// xhr.onload = function() {
    
    
				// 	if (xhr.readyState === 4 && xhr.status === 200) {
    
    
				// 		let blob = this.response;
				// 		// 转换一个blob链接
				// 		let u = window.URL.createObjectURL(new Blob([blob]));
				// 		let a = document.createElement('a');
				// 		a.download = 'test.mp4'; //下载后保存的名称
				// 		a.href = u;
				// 		a.style.display = 'none';
				// 		document.body.appendChild(a);
				// 		a.click();
				// 		a.remove();
				// 		uni.hideLoading();
				// 		that.showVideo = true;
				// 	}
				// };
				// xhr.send()
			 
			}				
		}
	}
</script>

<style>
	.bg-set {
    
    
		width: 100%;
	}

	.btn-set {
    
    
		height: 87rpx;
		width: 253rpx;
		position: absolute;
		z-index: 1000;
		top: 10%;
		left: 50%;
		transform: translateX(-50%) translateY(-50%);
	}

	.videoPoster {
    
    
		width: 79%;
		height: 71%;
		border-radius: 10rpx;
		overflow: hidden;
		background-color: #333333;
		position: absolute;
		z-index: 1000;
		top: 54%;
		left: 50%;
		transform: translateX(-50%) translateY(-50%);
		/* 水平垂直居中 要与上方的top,left配合使用*/
	}

	video {
    
    
		width: 100%;
		height: 100%;
	}
	
</style>

猜你喜欢

转载自blog.csdn.net/weixin_38946164/article/details/116134231