天天看點

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()           

這個也不用注釋了...

繼續閱讀