前端js通过链接下载文件
axios({
method: 'get',
url: `http://xxxx.mp4`,
// 必须显式指明响应类型是一个Blob对象,这样生成二进制的数据,才能通过window.URL.createObjectURL进行创建成功
responseType: 'blob',
}).then((res) => {
if (!res) {
return
}
// 将blob对象转换为域名结合式的url
let blobUrl = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
document.body.appendChild(link)
link.style.display = 'none'
link.href = blobUrl
// 设置a标签的下载属性,设置文件名及格式,后缀名最好让后端在数据格式中返回
link.download = 'city-video.mp4'
// 自触发click事件
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(blobUrl);
})
如果我们要使用原生xmlHttpRequest,方式也是一样的,只要指定请求返回值类型为blob
就可以了
var url = 'http://xxxx.mp4';
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // 只需要将返回值类型设置为blob就可以了
xhr.open(method, url);
// 请求出错
xhr.onerror = function(err) {
console.log(err);
}
// 请求结束
xhr.onloadend = function(msg) {
console.log(msg);
}
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
const status = xhr.status;
if ((status >= 200 && status < 300) || status === 304) {
// 将blob对象转换为域名结合式的url
let blobUrl = window.URL.createObjectURL(xhr.response);
let link = document.createElement('a')
document.body.appendChild(link)
link.style.display = 'none'
link.href = blobUrl
// 设置a标签的下载属性,设置文件名及格式,后缀名最好让后端在数据格式中返回
link.download = 'city-video.mp4'
// 自触发click事件
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(blobUrl);
} else {
console.log('请求错误');
}
}
xhr.send(null);