如何通过Office Viewer在浏览器中预览Base64或Blob格式的docx文件
问题
目标:通过简单的<object />容器,使用JavaScript/HTML在浏览器中预览Base64(或Blob)格式的*.docx*文件。
现有可正常预览公开路径文档的方案如下,但持有的文档没有公开访问路径,仅能向终端浏览器传输Base64或Blob格式的内容:
<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>
现在持有文档对应的Base64格式内容,如何调用office viewer来展示该文件?
解决方案
你使用的
https://view.officeapps.live.com官方Office预览服务仅支持传入公网可直接访问的文档URL作为参数,不支持直接传入Base64、Blob格式的私有文档内容,因此无法直接用该服务加载你手里的Base64格式docx文件。
方案一:纯前端无服务依赖实现(推荐)
使用前端docx解析库直接在浏览器侧渲染文档,无需将文档上传到公网,也不依赖外部预览服务,支持直接输入Base64或Blob格式内容。
实现代码示例
<!-- 预览容器,你也可以替换为<object>容器 --> <div id="docx-container" style="width: 100%; height: 800px;"></div> <script> // Base64转Blob工具函数 function base64ToBlob(base64, mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') { const byteCharacters = atob(base64); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += 512) { const slice = byteCharacters.slice(offset, offset + 512); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, { type: mimeType }); } // 替换为你的docx文件Base64内容 const docxBase64 = '你持有的docx文件Base64字符串'; const docxBlob = base64ToBlob(docxBase64); // 引入docx解析库后调用渲染方法 docx.renderAsync(docxBlob, document.getElementById('docx-container')) .then(() => { // 渲染成功逻辑 }) .catch(err => { // 渲染失败处理逻辑 }); </script>
方案二:配合临时存储使用官方Office预览服务
如果必须使用微软官方预览服务,需要新增后端逻辑配合实现:
- 前端将Base64格式的文档上传到后端服务
- 后端将文档存储后生成一个临时的、公网可访问的文档URL,可按需设置URL有效期
- 将生成的临时URL传入Office预览服务的
src参数即可沿用原有iframe方案预览
<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=替换为后端生成的临时公网URL' width='1366px' height='623px' frameborder='0'> </iframe>
内容的提问来源于stack exchange,提问作者DavidDunham
相关产品推荐
相关产品推荐

