通过ajax实现文件下载到本地

const downloadFile = (ajaxUrl, callBack = () => { }) => {
  const xhr = new XMLHttpRequest()
  xhr.open("GET", ajaxUrl, true)
  // responseType若不设置,会导致下载的文件可能打不开
  xhr.responseType = "blob"
  xhr.onload = function () {
    if (this.status === 200 || this.status === 201) {
      const blob = this.response
      const reader = new FileReader()
      const jsonFlag = this.getResponseHeader('content-type').indexOf('application/json') !== -1
      jsonFlag ? reader.readAsText(blob) : reader.readAsDataURL(blob)
      reader.onload = function (e) {
        if (jsonFlag) {
          const result = JSON.parse(reader.result || '服务器出现问题,请联系管理员')
          message.error(result.code)
        } else {
          const disposition = xhr.getResponseHeader("Content-disposition")
          const _fileName = decodeURIComponent(disposition.split(';')[1].trim().slice(9));
          const a = document.createElement("a")
          const event = new MouseEvent('click')
          a.download = _fileName
          a.href = e.target.result
          a.dispatchEvent(event)
        }
        callBack()
      }
    } else {
      callBack()
      message.error('服务器出现问题,请联系管理员')
    }
  }
  xhr.send()
}
复制代码
分类:
前端
标签: