Bootstrap

vue 导出excel接口请求和axios返回值blob类型处理

1. 导出功能vue文件代码

// 导出
const exportData = () => {
	const param = {
		warehouseId: warehouseId.value,
		dispatchType: dispatchType.value,
		beginTime: rangeTime.value?.length ? rangeTime.value[0] : undefined,
		endTime: rangeTime.value?.length ? rangeTime.value[1] : undefined
	}
	otherAPI.exportActionStatistics(param, 'blob').then((res: any) => {
		let fileName = '任务统计'
		let url = window.URL.createObjectURL(new Blob([res.data]))
		let link = document.createElement('a')
		link.style.display = 'none'
		link.href = url
		link.id = 'Adownload'
		link.setAttribute('download', `${fileName}.xlsx`) //命名可能会出现问题,格式一定和后端下载的格式一样
		document.body.appendChild(link)
		link.click()
	})
}

2. 接口方法代码

	// 任务导出
	exportActionStatistics(params: any, responseType: any) {
		const obj = {}
		if (params) {
			AiObject.cloneTo(params, obj)
		}
		return REST.request(HTTPMethod.GET, this.server + 'Statistics/ExportActionStatistics' + AiObject.toQueryString(obj), undefined, undefined, responseType)
	}

3. axios封装代码(REST.ts) 包含导出接口报错时返回blob的数据处理

const service = axios.create({
	headers: {
		// 'Access-Control-Allow-Origin': '*',
		// 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
		// 'content-Type': 'application/json; charset=utf-8'
	}
})

// 请求拦截
service.interceptors.request.use(
	(config: AxiosRequestConfig | any) => {
		// 增加一种情况授权,授权之后再登录
		if (window.sessionStorage.getItem('unlicensed') === '1') {
			// 系统未授权的判断要跑到未登录判断的前面。
		} else {
			const token = sessionStorage.getItem('token')
			if (token && config.headers) {
				config.headers.Authorization = token
			} else {
				Auth.singleton.logout()
			}
		}
		return config
	},
	(error: any) => {
		Promise.reject(error)
	}
)

// 响应拦截
service.interceptors.response.use(
	(response) => Promise.resolve(response),
	(error: any) => {
		// 授权失败
		if (error?.response?.status === HTTPStatus.Unlicensed) {
			window.sessionStorage.setItem('unlicensed', '1')
			Global.router.push({ path: '/lockdown' })
		} else if (error?.response?.status === HTTPStatus.Unauthorized) {
			Auth.singleton.logout()
		} else if (error && error.response) {
			if (error.response.data instanceof Blob) {
				// 针对 Blob 类型错误处理
				const res = error.response
				const fileReader: any = new FileReader()
				fileReader.readAsText(new Blob([res.data], { type: 'application/octet-stream' }), 'utf-8')
				fileReader.onload = () => {
					const { message } = JSON.parse(fileReader.result)
					ElMessage({
						showClose: true,
						message: message,
						type: 'error'
					})
				}
			} else {
				ElMessage({
					showClose: true,
					message: error.response.data.message,
					type: 'error'
					// duration: 0
				})
			}
		} else {
			ElMessage.error('连接到服务器失败,请联系管理员')
		}
		return Promise.reject(error)
	}
)

ResponseType传入判断 

	static request(method: HTTPMethod, url: string, params?: string | number | { [key: string]: any }, className?: string, responseType?: ResponseType): AxiosPromise {
		// 如果有className 就得额外增加进去。
		if (typeof className === 'string') url += className

		// 确保参数符合 AxiosRequestConfig 接口。
		const config: AxiosRequestConfig = {
			method
		}
		if (responseType) {
			config.responseType = responseType as any
		}

		switch (typeof params) {
			case 'number':
			case 'string':
				config.url = `${url}${params}`
				break
			case 'object':
				config.url = url
				config.data = params
				break
			default:
				config.url = url
				break
		}

		if (responseType) {
			config.responseType = responseType
		}

		return service(config)
	}

;