文档的打开与下载-浏览器兼容

80 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天,点击查看活动详情

文件下载?简单啊,a标签的download属性,然后点击即下载。

www.w3school.com.cn/tags/att_a_…

官方也说了只有 Firefox 和 Chrome 支持 download 属性。

那我IE11怎么办,于是我开始了无尽的百度与尝试。

方法一:window.open没用,只是打开文件。

let output = '/static/download/aaa.txt'
let downloadFileName = 'testa'
if (window.navigator.msSaveBlob) {
    // for ie 10 and later
    try {
        let blobObject = new Blob([output])
        window.navigator.msSaveBlob(blobObject, downloadFileName)
    } catch (e) {
        console.log(e)
    }
} else {
    let file = 'data:text/plain;charset=utf-8,'
    let logFile = output
    let encoded = encodeURIComponent(logFile)
    file += encoded
    let a = document.createElement('a')
    a.href = file
    a.target = '_blank'
    a.download = downloadFileName
    document.body.appendChild(a)
    a.click()
    a.remove()
}

方法二:iframe没用,只是打开没用下载功能。

let elemIF = document.createElement('iframe')
elemIF.style.display = 'none'
elemIF.src = '/static/download/aaa.txt'
document.body.appendChild(elemIF)
elemIF.click()

方法三:IE11的msSaveOrOpenBlob函数

估计有效,但是这个通常用于将页面内容获取写入fileContent,然后下载,然而我是已存在文件aaa.txt。

let fileName = '/static/download/aaa.txt' // 文件地址
let downName = 'test' // 文件下载名称
const blob = new Blob([fileContent])
if (window.navigator.msSaveOrOpenBlob) {
    // 兼容IE10
    navigator.msSaveBlob(blob, downName)
} else {
    // chrome/firefox
    let aTag = document.createElement('a')
    aTag.download = downName
    aTag.href = URL.createObjectURL(blob)
    aTag.click()
    URL.revokeObjectURL(aTag.href)
}

方法四:execCommand('SaveAs')

没用,保存整个网页可能有用吧,没有尝试成功。

let oPop = window.open('/static/download/aaa.txt', '', 'width=500, height=500, top=5000, left=5000')
for (; oPop.document.readyState !== 'complete';) {
    if (oPop.document.readyState === 'complete') {
        break
    }
}
oPop.document.execCommand('SaveAs')
oPop.close()

方法五:同事的代码

他们的系统有用,然而我这不起作用,说白了还是创建了一个a标签,不应该有用不知道他们系统为什么可以。

let obj = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
obj.href = '/static/download/aaa.txt'
obj.download = 'test.txt'
let ev = document.createEvent('MouseEvents')
ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
obj.dispatchEvent(ev)

方法六:window.location.href没用,只是打开文件。

// window.location.href = '/static/download/aaa.txt'

方法七:最初提到的常用的a标签方法,IE不支持

let url = '/static/download/aaa.txt'
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'aaa.txt')
document.body.appendChild(link)
link.click()

方法八:最后还是调用了后台的下载接口,适用于所有浏览

let url = this.$_apiUrl.download
window.open(url + '?name=aaa.txt')

注意:此处默认是get请求。