今天所遇到的需求是后端返回html的二进制流,前端进行处理展示,话不多说,直接上代码。
第一步:接口处理
export async function getHtml(params: any): Promise<any> {
return request(`${codeDependencyApi}/qtScan/download/html`, {
params,
responseType: 'blob',
});
}
⚠️:请求类型记得写 blob, 前提是项目中的请求拦截器已经配置好
第一步:处理接口数据
getHtml({ jobId, buildId: buildNumber }).then(res => {
const blob_ = new Blob([res], { type: 'text/html' }) // 解释成html文件
const fileURL = URL.createObjectURL(blob_); //拿到blob转换的缓存中的地址
console.log("fileURL", fileURL);
setDocUrl(fileURL)
}).finally(() => {
setLoading(false)
})
⚠️:这里用的是react+umi, 大体都会差不多,重点是拿到blob转换的地址
最后, 拿到地址后塞到<iframe> 标签里即可,现在就处理完成了
<div id='test'>
<iframe src={docUrl} width="100%" height="600px" />
</div>
ps: 最开始让后端返回的是string字符串类型的格式,想dangerouslySetInnerHTML直接转换成html,但是css转换不完全,且影响到全局样式进行样式污染,同时也渲染不出来js。