Vue如何实现从response读取流下载

Vue从response读取流下载

1、创建公共方法

/**
 * 从response读取流下载
 * @param response 响应体
 * @param suffix 文件后缀名
 */
function downloadBlob(response,suffix){

  let fileName = new Date().getTime()+"_"+suffix+'.xlsx'
  let blob = new Blob([response]);//response.data为后端传的流文件
  let url = window.URL.createObjectURL(blob);
  let downloadElement = document.createElement("a");
  downloadElement.style.display = "none";
  downloadElement.href = url;
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(url);
}

export default {
  downloadBlob
}

2、挂载到Vue原型上

import blob from '@/utils/blob'
Vue.prototype.$blob = blob

3、使用

/** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否导出所有数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportData();
        }).then(response => {
          this.$blob.downloadBlob(response,"数据表")
        }).catch(()=>{})
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源链接:https://www.jb51.net/javascript/339474vam.htm

© 版权声明
THE END
支持一下吧
点赞13 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容