文章目录
前言
对接onlyoffice,实现文档的预览和在线编辑功能。
一、vue + ts
1. 安装依赖
npminstall--save @onlyoffice/文档-editor-vue
# oryarnadd @onlyoffice/document-editor-vue
2. onlyoffice组件实现
<template><DocumentEditorid="docEditor":documentServerUrl="documentServerUrl":config="config"/></template><scriptlang="ts"setup>import type {IConfig}from"@onlyoffice/document-editor-vue";import{DocumentEditor}from"@onlyoffice/document-editor-vue";
defineProps<{documentServerUrl: string,config: IConfig
}>()</script>
3. 使用组件
<template><divclass="container_div"><back-history:msg="fileName"/><only-office:documentServerUrl="getGlobalConfig().onlyOffice.documentServerUrl":config="config"/></div></template><scriptsetuplang="ts">import onlyOffice from'../../components/onlyOffice.vue'import{reactive, ref}from"vue"import BackHistory from"@/components/BackHistory.vue"import Guid from'guid'import{useRoute}from"vue-router"import{getGlobalConfig}from"@/utils/globalConfig"let route =useRoute()let data =JSON.parse(decodeURIComponent(<string>route.query.params))let fileId = data.id
let title =ref(data.fileName)let fileName =ref(title.value.slice(0, title.value.lastIndexOf('.')))let fileType = data.ext
//从配置文件读取onlyoffice配置const editorConfig =getGlobalConfig().onlyOffice.editorConfig
editorConfig.callbackUrl += fileId
functionhandleDocType(fileType){let docType ='';let fileTypesDoc =['doc','docm','docx','dot','dotm','dotx','epub','fodt','htm','html','mht','odt','ott','pdf','rtf','txt','djvu','xps'];let fileTypesCsv =['csv','fods','ods','ots','xls','xlsm','xlsx','xlt','xltm','xltx'];let fileTypesPPt =['fodp','odp','otp','pot','potm','potx','pps','ppsm','ppsx','ppt','pptm','pptx'];if(fileTypesDoc.includes(fileType)){
docType ='word'}if(fileTypesCsv.includes(fileType)){
docType ='cell'}if(fileTypesPPt.includes(fileType)){
docType ='slide'}return docType;}let config ={documentType:handleDocType(fileType),document: reactive<any>({fileType: fileType,key: Guid.raw(),title: title,url: data.url
}),editorConfig: editorConfig,height:'850'}</script>
4. 我的配置文件
{"onlyOffice":{"documentServerUrl":"onlyoffice 服务地址","editorConfig":{"callbackUrl":"http://172.0.0.139:8095/api/gsdss/file/v1/onlyoffice/save?fileId=","lang":"zh-CN"}}}
二、springboot 回调代码
1. 本地存储
/**
* onlyOfficeCallBack
*/@ApiOperationSupport(order =10)@PostMapping(value ="/v1/onlyoffice/save")publicStringonlyOfficeCallBack(String fileId,HttpServletRequest request,HttpServletResponse response){return service.onlyOfficeCallBack(request, response, fileId);}@OverridepublicStringonlyOfficeCallBack(HttpServletRequest request,HttpServletResponse response,String fileId){Scanner scanner;try{
scanner =newScanner(request.getInputStream()).useDelimiter("\\A");String body = scanner.hasNext()? scanner.next():"";OfficeFileResp jsonObj =JsonUtil.of(body,OfficeFileResp.class);if(jsonObj.getStatus()==2){String downloadUri = jsonObj.getUrl();URL url =newURL(downloadUri);HttpURLConnection connection =(java.net.HttpURLConnection) url.openConnection();InputStream stream = connection.getInputStream();//查询附件信息,以获取附件存储路径AttachmentPO po =findById(fileId);File savedFile =newFile(po.getPath());try(FileOutputStream out =newFileOutputStream(savedFile)){int read;finalbyte[] bytes =newbyte[1024];while((read = stream.read(bytes))!=-1){
out.write(bytes,0, read);}
out.flush();}
connection.disconnect();}return"{\"error\":0}";}catch(IOException e){thrownewBusinessException("onlyOffice 保存回调失败", e);}}
三、效果展示
修改离开当前页面后会自动触发保存,大约5秒后下载文件,文件已经是最新。
踩坑总结
问题1
The document could not be saved. Please check connection settings or
contact your administratorWhen you click the ‘Ok’ button, you will be
prompted to download the document.
(这份文件无法保存。请检查连接设置或联系您的管理员当你点击“OK“按钮,系统将提示您下载文档。)
回调接口不通导致,callbackUrl必须是onlyoffice所在服务器可访问的接口地址,可以进入docker镜像内部查看onlyoffice日志就会有所发现。
dockerexec-it 【镜像id】/bin/bash
tail-f /var/log/onlyoffice/documentserver/docservice/out.log-20230805
Error: connect ECONNREFUSED 127.0.0.1:8194
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
[2023-08-07T00:57:50.813] [ERROR] nodeJS - postData error: docId = fc5d1b8f6211403fa8788661007ccd42;url = https://localhost:8194/api/gsdss/file/v1/onlyoffice/save;data = {“key”:“fc5d1b8f6211403fa8788661007ccd42”,“status”:1,“users”:[“uid-1691118844328”],“actions”:[{“type”:1,“userid”:“uid-1691118844328”}]}
问题2
文件版本已更改(The file version has been changed)
document.key 每次编辑和保存文档时,都必须重新生成,目前采用的guid,但是没有捕获编辑后保存的事件去改变,而是每次加载都用新的key
有价值的参考:
- https://www.onlyoffice.org.cn/guide/parameters.html
- https://blog.csdn.net/qq_43548590/article/details/129948103
- https://www.jianshu.com/p/2d4f977ffeac
- https://api.onlyoffice.com/editors/config/
- https://devpress.csdn.net/viewdesign/64084b4b986c660f3cf917ba.html
版权归原作者 Mr-Wanter 所有, 如有侵权,请联系我们删除。