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)
	}
相关推荐
就改了几秒前
Ajax——在OA系统提升性能的局部刷新
前端·javascript·ajax
凌冰_2 分钟前
Ajax 入门
前端·javascript·ajax
京东零售技术17 分钟前
京东小程序JS API仓颉改造实践
前端
奋飛27 分钟前
TypeScript系列:第六篇 - 编写高质量的TS类型
javascript·typescript·ts·declare·.d.ts
老A技术联盟27 分钟前
从小白入门,基于Cursor开发一个前端小程序之Cursor 编程实践与案例分析
前端·小程序
风铃喵游30 分钟前
构建引擎: 打造小程序编译器
前端·小程序·架构
sunbyte35 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ThemeClock(主题时钟)
前端·javascript·css·vue.js·前端框架·tailwindcss
小飞悟44 分钟前
🎯 什么是模块化?CommonJS 和 ES6 Modules 到底有什么区别?小白也能看懂
前端·javascript·设计
浏览器API调用工程师_Taylor44 分钟前
AOP魔法:一招实现登录弹窗的全局拦截与动态处理
前端·javascript·vue.js
FogLetter1 小时前
初识图片懒加载:让网页像"懒人"一样聪明加载
前端·javascript