导出下载公共方式(后台返回文件流或文件地址)

以下方法是后台返回文件流(从文件头里取类型,可下载任何类型的文件)

接口请求

下载一般类型:

/**
 * download file下载文件
 */
export const downloadBlobFile = (res, fileNameS) => {
  if (!res) {
    return
  }
  let contentType = res.headers['content-type'];
  const blob = new Blob([res.data], {
    type: contentType
  })
  let fileName = ''
  if(fileNameS) {
    fileName = `${fileNameS}`
  } else {
    fileName = res.headers['content-disposition'] ? decodeURI(escape(res.headers['content-disposition'].split(';')[1].split('=')[1])) : '';
  }
  debugger
  let a = document.createElement("a");
  let url = window.URL.createObjectURL(blob);
  console.log(blob)
  a.setAttribute("href", url)
  a.download = fileName
  document.body.appendChild(a);
  a.click()
  document.body.removeChild(a);
}

下载blobjson类型:

// 下载bolbjson
export const downloadBlobJson = (data, fileNameS = 'json') => {
  if (!data) {
    return
  }
  // console.log(data)
  const blob = new Blob([JSON.stringify(data)])
  const fileName = `${fileNameS}.json`
  if ('download' in document.createElement('a')) { // 不是IE浏览器
    const url = window.URL.createObjectURL(blob)    
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下载完成移除元素
    window.URL.revokeObjectURL(url) // 释放掉blob对象
  } else { // IE 10+
    window.navigator.msSaveBlob(blob, fileName)
  }
}

 

 

以下方法是后台返回文件地址

一般文件的导出: 

 /**
 * @param attachPath  导出路径
 * @return 导出文件
 */
export const downloadFile =(attachPath)=> { 
    var $a = document.createElement('a');
    $a.setAttribute("href", attachPath);
    $a.setAttribute("download", "");
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
    $a.dispatchEvent(evObj);
}

 跨域文件导出下载方法

 /**
 * @param url  导出路径
 * @param fileName  文件名
 * @return 跨域文件路径、下载到本地的文件名
 */
export const downloadFileBlob =(url,fileName)=> { 
    var x = new XMLHttpRequest();
    x.open("GET", url, true);
    x.responseType = 'blob';
    x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = fileName;
        a.click()
    }
    x.send();
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值