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)
	}
相关推荐
浩星8 分钟前
iframe引入界面有el-date-picker日期框,点击出现闪退问题处理
前端·vue.js·elementui
技术钱10 分钟前
element plus 多个form校验
前端
yume_sibai19 分钟前
HTML HTML基础(3)
前端·html
米花丶26 分钟前
JSBridge安全通信:iOS/Android桥对象差异与最佳实践
前端·webview
唐•苏凯1 小时前
ArcGIS Pro 遇到严重的应用程序错误而无法启动
开发语言·javascript·ecmascript
萌萌哒草头将军1 小时前
🚀🚀🚀 Oxc 恶意扩展警告;Rolldown 放弃 CJS 支持;Vite 发布两个漏洞补丁版本;Rslib v0.13 支持 ts-go
前端·javascript·vue.js
接着奏乐接着舞。1 小时前
3D地球可视化教程 - 第1篇:基础地球渲染系统
前端·javascript·vue.js·3d·three.js
龙傲天6661 小时前
Scala的面向对象和函数式编程特性 Idea环境搭建和输入输出
前端
蓝色海岛1 小时前
element-ui表格嵌套表格,鼠标移入时样式错乱-问题调研及处理办法
前端
薄雾晚晴1 小时前
Rspack 实战:用 SWC Loader 搞定 JS 兼容(支持 IE 11 + 现代浏览器,兼顾构建速度)
前端·vue.js