js下载文件 兼容性写法

// 通用下载方法
export function download(fileName) {
  /*
  * 使用window.location.href pc端下载正常,平板下载后文件内容为空
  * // window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
  * */

  //兼容平板下载的写法
  var url = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
  var fileName = fileName;
  ajax(url, function(xhr) {
    downloadFile(xhr.response, fileName)
  }, {
    responseType: ‘blob‘
  })
}

//下载文件1
function downloadFile(content, filename) {
  var a = document.createElement(‘a‘)
  var blob = new Blob([content])
  var url = window.URL.createObjectURL(blob)
  a.href = url
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(url)
}
//下载文件2
function ajax(url, callback, options) {
  window.URL = window.URL || window.webkitURL
  var xhr = new XMLHttpRequest()
  xhr.open(‘get‘, url, true)
  if (options.responseType) {
    xhr.responseType = options.responseType
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr)
    }
  }
  xhr.send()
}

 

js下载文件 兼容性写法

上一篇:http缓存中etag的生成原理


下一篇:js触屏事件