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()
这个也不用注释了...