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

  1. 导出功能vue文件代码
javascript 复制代码
// 导出
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()
	})
}
  1. 接口方法代码
javascript 复制代码
	// 任务导出
	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)
	}
  1. axios封装代码(REST.ts) 包含导出接口报错时返回blob的数据处理
javascript 复制代码
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传入判断

javascript 复制代码
	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)
	}
相关推荐
码事漫谈2 小时前
大模型输出的“隐性结构塌缩”问题及对策
前端·后端
这儿有一堆花2 小时前
前端三件套真的落后了吗?揭开现代 Web 开发的底层逻辑
前端·javascript·css·html5
.Cnn3 小时前
JavaScript 前端基础笔记(网页交互核心)
前端·javascript·笔记·交互
醉酒的李白、3 小时前
Vue3 组件通信本质:Props 下发,Emits 回传
前端·javascript·vue.js
anOnion3 小时前
构建无障碍组件之Window Splitter Pattern
前端·html·交互设计
小眼哥3 小时前
SpringBoot整合Vue代码生成exe运行程序以及windows安装包
vue.js·windows·spring boot
NotFound4863 小时前
实战分享Python爬虫,如何实现高效解析 Web of Science 文献数据并导出 CSV
前端·爬虫·python
徐小夕4 小时前
PDF无限制预览!Jit-Viewer V1.5.0开源文档预览神器正式发布
前端·vue.js·github
WangJunXiang64 小时前
Haproxy搭建Web群集
前端
吴声子夜歌4 小时前
Vue.js——自定义指令
前端·vue.js·flutter