js下载文件常用的两种方式

1、后端直接返回文件服务器地址,前端创建a标签模拟

export function downloadFileUrl (url, fileName) {

  const elink = document.createElement('a')

  elink.href = url

  elink.setAttribute('download', fileName)

  elink.style.display = 'none'

  document.body.appendChild(elink)

  setTimeout(() => {

    elink.click()

    document.body.removeChild(elink)

  }, 66)

}

上述方法参数url表示后端返回的文件地址,fileName表示下载的文件名称,本人查询了download属性的兼容性,的确ie11及一下不兼容,图片和pdf时会直接打开,压缩包文件的话全部能正常下载(ie是11及以上),直接打开的图片和pdf这是浏览器机制问题。

2、后端返回二进文件流,前端使用blob进行文件下载

export function downloadFileStream (fileStream, name, extension, type = '') {

  const blob = new Blob([fileStream], {type})

  const fileName = `${name}.${extension}`

  if ('download' in document.createElement('a')) {

    const elink = document.createElement('a')

    elink.download = fileName

    elink.style.display = 'none'

    elink.href = URL.createObjectURL(blob)

    document.body.appendChild(elink)

    elink.click()

    URL.revokeObjectURL(elink.href)

    document.body.removeChild(elink)

  } else {

    // 兼容IE10+下载

    navigator.msSaveBlob(blob, fileName)

  }

}

返回参数注释:fileStream返回流,name文件名称,extension文件后缀类型, type为文件类型

excel的话为application/vnd.ms-excel

注意axios请求时返回类型为responseType = 'blob'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值