Post方式在前端下载文件

const token = JSON.parse(localStorage.getItem('_token')).token;
const requestBody= {};
const url = '';
const xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.responseType = 'blob';

const thisClone = this;
this.isShowDownload = true;
xhr.onprogress = function (event) {
	if (event.lengthComputable) {
		thisClone.progress = Number((event.loaded * 100 / event.total).toString().split('.')[0]);
	}
};

xhr.onload = function (e) {
	if (this.status === 200) {
		const blob = this.response;
		const link = document.createElement('a');
		const val = URL.createObjectURL(blob);
		link.href = val;
		link.download =  'xxx.zip';
		link.click();
		window.URL.revokeObjectURL(url);
		
		thisClone.progress = 0;
		thisClone.isShowDownload = false;
	} else {
		thisClone.progress = 0;
		thisClone.isShowDownload = false;
	}
};

xhr.send(JSON.stringify(requestBody));

你可能感兴趣的:(Typescript)