1. 背景介绍
近期封装obs上传、下载工具包时,调用obs下载接口时无法下载到本地,直接用window.open(url)时,有的文件只能预览不能下载,无奈只能另寻他路了。
2. 问题研究
window.open(url)
文件只预览不下载,可能因同源问题使浏览器无法打开文件下载框,导致文件不能下载。emmmm,百度上这么说的,具体原因本人也未寻到,有缘人见此可为小弟解答12~~~
3. 解决方案
/**
* 前端下载文件功能实现
* @param {String} filePath 文件下载路径
* @param {String} fileName 文件下载到本地的名称
*/
function downloadFile(filePath, fileName) {
if(filePath) {
var x = new XMLHttpRequest();
x.open("GET", filePath, true);
x.responseType = 'blob';
x.onload=function() {
let url = window.URL.createObjectURL(x.response)
let link=document.createElement('a') // 创建a标签
link.style.display = 'none'
link.target = '_target'
link.href = url // 设置下载地址
link.download = fileName || '' // 添加downLoad属性
document.body.appendChild(link)
link.click()
}
x.send()
} else {
console.log('暂无可下载文件!')
}
}
上述方法在非同源下载时,不会识别文件类型,需要手动去定义文件的类型,或者在调用此方法时传
入fileName,定义下载的文件名称。
4. 其他方案(非同源)
// 方案1 -- 调用window.open在浏览器打开下载
window.open(url)
// 利用 a 标签的 download 属性 -- 设置 download 属性也不下载时考虑是否是同源问题引起的
let link=document.createElement('a') // 创建a标签
link.style.display = 'none'
link.target = '_target'
link.href = url // 设置下载地址
link.download = fileName || '' // 添加downLoad属性
document.body.appendChild(link)
link.click()