Angular中使用ngx-doc-viewer预览刚编辑的Docx文档时出现404错误
问题分析与解决方案
核心诱因
WPS Office编辑后的docx文件存在后台文件锁定/延迟写入特性:即便手动点击保存,WPS仍可能在后台占用文件资源,导致上传的文件内容不完整或元数据异常;普通文档无此问题,因此排除Blob存储上传完整性问题,核心矛盾集中在WPS的文件处理逻辑上。
具体解决办法
上传前确保文件完全释放
禁止在WPS打开文件的状态下上传,必须关闭WPS后再选择文件。如果是自动化上传场景,可在前端通过读取文件完整二进制内容做验证:读取失败则提示用户关闭编辑软件重试。示例代码:async validateFile(file: File): Promise<boolean> { try { await file.arrayBuffer(); return true; } catch (e) { console.error('文件被占用,请关闭WPS后重试'); return false; } }修改Blob存储缓存策略
上传Blob时设置Cache-Control响应头为no-cache, no-store,避免ngx-doc-viewer请求时命中无效缓存。以常见Blob存储上传配置为例:const uploadOptions = { headers: { 'Cache-Control': 'no-cache, no-store' } }; // 上传时传入该配置给ngx-doc-viewer添加重试逻辑
监听组件错误事件,捕获404后延迟重试加载。示例代码:<ngx-doc-viewer #docViewer [url]="blobUrl" (error)="handlePreviewError($event)"></ngx-doc-viewer>@ViewChild('docViewer') docViewer: DocViewerComponent; private retryTimes = 0; private maxRetry = 3; handlePreviewError(event: any) { if (event.status === 404 && this.retryTimes < this.maxRetry) { this.retryTimes++; setTimeout(() => { this.docViewer.refresh(); }, 1500); } }预处理WPS生成的docx文件
用JSZip库重新打包docx,修复可能存在的格式异常。示例代码:import * as JSZip from 'jszip'; async fixWpsDocx(file: File): Promise<Blob> { const zip = await JSZip.loadAsync(file); return zip.generateAsync({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); } // 上传时使用处理后的Blob对象
内容的提问来源于stack exchange,提问作者Srichand Malladi
相关产品推荐
相关产品推荐

