文件下载,公共组件基于XMLHttpRequest+blob

29 篇文章 2 订阅
11 篇文章 0 订阅

封装成组件,多了一个element按钮的对象属性,bottonObj集成element原生属性,参考自定义样式。

文件下载参数 fileName(必传,看和后端约定,可以在response的header中返回文件名称)params(请求参数非必传)requestType(请求类型非必传,默认get)

*另外请求地址采用获取配置文件的方式,token直接获取localStorage。可以根据实际项目约定修改。

1、组件源码 main.vue

<template>
	<div>
		<el-button :size="bottonObj.size"
			:type="bottonObj.type"
			:plain="bottonObj.plain"
			:round="bottonObj.round"
			:circle="bottonObj.circle"
			:loading="loading"
			:disabled="bottonObj.disabled"
			:icon="bottonObj.icon"
			@click="download">{{bottonObj.text || '下载'}}</el-button>
	</div>
</template>

<script>
	import main from './main.js';
	export default {
		name: 'z-download',
		props: {
			bottonObj: {
				type: Object,
				default: () => {
					return {}
				}
			},
			fileName: {
				type: String,
				required: true
			},
			params: {
				type: Object,
				default: () => {
					return {}
				}
			},
			requestType: {
				type: String,
			}
		},
		data() {
			return {
				loading: false,

			}
		},
		methods: {
			async download() {
				this.loading = true;
				let res = await main(this.fileName, this.params, this.requestType);
				if (res) {
					this.loading = false;
				}
			}
		}
	}
</script>

2、main.js

/**
 * @createDate 2022年11月10日
 * @name 导出文件名称
 * @params 请求参数
 * @type 请求类型
 */
export default (fileName, params = '', type = 'GET') => {
	return new Promise((resolve, reject) => {
		const url = process.env.VUE_APP_BASE_DOWNLOAD_URL
		type = type.toUpperCase();
		let xhr = new XMLHttpRequest();
		if (type === 'POST') {
			let data = params ? JSON.stringify(params) : {};
			xhr.open('POST', url, true);
			xhr.responseType = 'blob';
			xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
			xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));
			xhr.send(data);
			xhr.onload = function() {
				if (this.status === 200) {
					let blob = this.response;
					let a = document.createElement('a');
					let aUrl = window.URL.createObjectURL(blob);
					a.href = aUrl;
					a.download = fileName;
					a.click();
					a.remove()
				}
			};
			resolve(xhr)
		} else {
			let newUrl = url;
			if (params) {
				let getParams = '?';
				for (let key in params) {
					if (params[key]) {
						getParams += `${key}=${params[key]}&`
					}
				}
				newUrl + url + getParams
			}
			xhr.open('GET', newUrl, true);
			xhr.responseType = 'blob';
			xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
			xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));
			xhr.send();
			xhr.onload = function() {
				if (this.status === 200) {
					let blob = this.response;
					let a = document.createElement('a');
					let aUrl = window.URL.createObjectURL(blob);
					a.href = aUrl;
					a.download = fileName;
					a.click();
					a.remove();
				}
			};
			resolve(xhr)
		}
	})
};

3、测试使用 testDownload.vue,当挂载全局,或者打包上传npm之后,只需要

<download fileName="测试文件.xlsx" />

这样一行几个字代码就能实现文件下载,岂不是美滋滋

<template>
	<download fileName="测试文件.xlsx" />
</template>

<script>
	import download from '../../../packages/z-download/src/main.vue'
	export default {
		components: {
			download
		},
	}
</script>

4、效果预览

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邹田聪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值