后台返回输出流,后台未找到结果集时,前台返回类型设置为输出流时,不用处理输出流,直接给出提示思路?

1.首先后台假如没有查找到结果集。在响应头添加一个新的标识tip,则用如图处理:

if (contentList == null || contentList.size() == 0) {
   response.addHeader("Access-Control-Expose-Headers", "tip");
   response.addHeader("tip", URLEncoder.encode("本月没有工作项!", "utf-8"));
   response.setStatus(404);
   return;
}

2.前台用原生的js发送请求并且接受到响应头,先判断状态码是不是等于404,等于404则先获取到新的标识tip 值,再用弹出框给出提示信息即可。

  

var fileName =this.form2.title + ".xls" //下载的文件;
var that = this;
var xhr = new XMLHttpRequest();
xhr.timeout = 3000;
xhr.open('post', that.exportPerMsgUrl, true);
xhr.setRequestHeader('content-type', 'application/json');
xhr.setRequestHeader("Authorization", "Bearer " + CookieUtil.mutations.getCookie("accessToken"));
//可以将`xhr.responseType`设置为`"blob"`也可以设置为`" arrayBuffer"`
//xhr.responseType = 'arrayBuffer';
xhr.responseType = 'blob';
xhr.onload = function(e) {
	if(this.status == 200) {
		const blob = this.response;
		if('download' in document.createElement('a')) { // 非IE下载
			const elink = document.createElement('a')
			elink.download = fileName;
			elink.style.display = 'none';
			elink.href = URL.createObjectURL(blob);
			document.body.appendChild(elink);
			elink.click();
			URL.revokeObjectURL(elink.href) // 释放URL 对象
			document.body.removeChild(elink)
			
			that.dialogFormVisible = false;
			that.form2.title ='';
			that.$refs[formName].resetFields();
			that.checkAll=false;
			that.checkedColumns = [];
			that.filterVal =[];
		} else { // IE10+下载
			navigator.msSaveBlob(blob, fileName)
		}
	}else if(this.status == 404) {
		var tip = decodeURIComponent(xhr.getResponseHeader('tip')); //未找到的文件名称
		if(tip != null) {
			that.$message({
				showClose: true,
				message: tip,
				type: 'error'
			});
		}
	}else {
		that.$message({
			showClose: true,
			message: '导出失败!',
			type: 'error'
		});
	}
};
xhr.send(JSON.stringify(param));

猜你喜欢

转载自blog.csdn.net/huxiaochao_6053/article/details/86592053