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