js(下载)将二进制转化为文件格式


说明: 主要是进行下载才使用的. 根据接口设计, 常见的下载方式主要有两种:

 

1. get请求

Vue.prototype.$downLoadImg = function(str) {
  let url = BASE_URL + "/download?path=" + str
  window.open(url);
};

 

2. post请求, 返回文件流, 需将其转化为文件.

在vue框架下的使用, 普通情况大同小异.

封装,可供全局使用:

Vue.prototype.$downloadFile =function(data, fileName){
  if (!data) {
    return
  }
  let url = window.URL.createObjectURL(new Blob([data]))
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click();
  link.remove();
 };

调用:

downFile () {
      api.DownLoad(this.checkForm).then(res => {
        let fileName = 'demo' + formatDate(new Date(),'yyyyMMdd')  + '.xlsx'
        this.$downloadFile(res, fileName);
      })
    },

发送请求时一定要设置responseType: 'blob', 否则转出的文件将会打不开:

export function DownLoad (data) {
  var uri = BASE_URL + '/api/downloadList'
  return fetch({
    url: uri,
    method: 'post',
    responseType: 'blob',
    data
  });
}

其中fetch是二次封装的axios,  BASE_URL是URL变量.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM