vue 里面 new Blob 流文件下载 完整步骤 直接享用

534 阅读1分钟

流文件下载 封装成方法,在utils文件夹下:

后期使用直接 引入就可以直接使用

@/utils/stream.js

  export default function ({
    url, // 请求地址
    method, // 请求类型
    data, // 请求参数
    fileName, // 请求名字
    suffix // 文件后缀
  }) {

    // axios请求
    axios({
        url,
        method,
        data,
        responseType: "blob",
        headers: {
          "Content-Type": "application/json",
          Authorization: 'token' // 拿项目本地的token
        }
      })
      .then(content => {

        const blob = new Blob([content]);// content 这里要和后台确认可能会多包裹一层 
        const a = document.createElement("a");
        const url = window.URL.createObjectURL(blob);
        const filename = fileName + suffix;
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);

        // 释放URL 对象
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      })

  }

页面中使用:

<script>
import stream from  @/utils/stream.js

export default {
	methods:{
	async down(){
		await stream({
				method: "post",
				url: "/api/downloadExcel",
				data: {name:'张三'},
				fileName: "班级成绩名单",
				suffix: ".xlsx",
			})
		}
	}
}
</script>