javascript 獲取接口返回的二進制blob 數據,後再轉爲對應mime 文件

src/config/util.js

export default{

    blobTofile(res, filename = null) {
        const blob = new Blob([res.data], { type: res.headers['content-type'] });
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;

        if (filename) {
          tempLink.setAttribute('download', filename);
        }
        tempLink.click()
        window.URL.revokeObjectURL(tempLink.href);
   }

}

axios  (注意 responseType="blob"  必須

export const trackingTpl = (data) => {
	return request('wms/order/tpl', 'get', data, false, 'blob');
};

@click="test"   test 方法

import  utils  from  '@/config/utils.js'

methods: {
    test() {
      trackingApi.trackingTpl().then(res => {
        console.log(res)
        utils.blobTofile(res)
      })
    }

}

最後:附上我的後端接口返回的數據格式,( 注意data 的類型是Blob, 很多小夥伴下載都打不開文件的,可能問題,就是返回的data 不是Blob)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章