准备:
onlyoffice/documentServer在线编辑保存
启动一个documentServer的容器
docker run -it --name documentServer -d -p 9090:80 onlyoffice/documentserver
使得可以访问http://localhost:9090/web-apps/apps/api/documents/api.js
============================================
VUE + ONLYOFFICE
基本配置使用
1 引入后台配置好的office服务器
<script type="text/javascript" src="https://documentserver/web-apps/apps/api/documents/api.js"></script>
2 封装组件
<template><div id="monitorOffice"></div>
</template>
<script>
import {handleDocType} from "../common/utils"export default {props: {option: {type: Object,default: () => {return {}}}},data() {return {doctype: ''}},mounted() {if (this.option.url)this.setEditor(this.option)},methods: {setEditor(option) {this.doctype = handleDocType(option.fileType);// office配置参数let config = {document: {fileType: option.fileType,key: "",title: option.title,permissions: {comment: false,download: false,modifyContentControl: true,modifyFilter: true,print: false,edit: option.isEdit,//是否可以编辑: 只能查看,传false// "fillForms": true,//是否可以填写表格,如果将mode参数设置为edit,则填写表单仅对文档编辑器可用。 默认值与edit或review参数的值一致。// "review": true //跟踪变化},url: option.url},documentType: this.doctype,editorConfig: {callbackUrl: option.editUrl,//"编辑word后保存时回调的地址,这个api需要自己写了,将编辑后的文件通过这个api保存到自己想要的位置lang: "zh",//语言设置customization: {autosave: false,//是否自动保存chat: false,comments: false,help: false,// "hideRightMenu": false,//定义在第一次加载时是显示还是隐藏右侧菜单。 默认值为falselogo: {image: "https://file.iviewui.com/icon/viewlogo.png",imageEmbedded: "https://file.iviewui.com/icon/viewlogo.png",},spellcheck: true,//拼写检查},},width: "100%",height: "100%",};let docEditor = new DocsAPI.DocEditor("monitorOffice", config);},},watch: {option: {handler: function (n, o) {this.setEditor(n);this.doctype = handleDocType(n.fileType);},deep: true,}}}
</script>
3 配置项参考官网
4 使用(一般就是编辑+查看两个功能)
<!--* @Author: zhengxiaoxiao* @Date: 2020-06-18 15:38:59* @Description: 监查报告
-->
<template><div class="monitor-report"><Upload ref="upload" accept=".doc,.docx" :action="action" :headers="header" :format="['doc','docx']":on-success="handleSuccess":show-upload-list="false" :before-upload="handleBeforeUpload" :on-format-error="handleFormatError"><Button :loading="loading" class="up-class">上传</Button><span>(文件格式为:doc,docx)</span></Upload><div class="office" v-if="pageLoading"><MonitorOffice :option="option"></MonitorOffice></div></div>
</template>
<script>// jsimport axios from "axios"import {GetMonitorReport} from "../../../../api/template"import {USER_NAME_SESSION, USER_ID_SESSION} from "../../../../common/storage";// 组件import MonitorOffice from "../../../../components/monitor-office"export default {components: {MonitorOffice},data() {return {// 上传文件参数header: {Authorization: `bearer ${sessionStorage.getItem("token")}`,},action: axios.defaults.baseURL + "/report/document/template",file: null,loading: false,// office配置参数option: {url: "",isEdit: false,fileType: "",title: ""},pageLoading: false}},mounted() {this.init();},methods: {init() {this.GetMonitorReport();},// 上传文件的格式验证handleFormatError(file) {this.$Message.warning(file.name + '格式不正确');this.loading = false;},// 上传之前handleBeforeUpload(file) {this.file = file;this.onUpload();return false;},onUpload() {this.loading = true;let _baseURL = axios.defaults.baseURL;this.action = `${_baseURL}/report/document/template`;setTimeout(() => {this.$refs.upload.post(this.file);}, 1000)},// 导入成功时handleSuccess(res) {this.loading = false;if (res.status) {this.$Message.success("上传成功");// 这里重新上传文件,only office不会覆盖,所以先刷新解决// location.reload();this.GetMonitorReport();}},// 获取项目下监察报告模板GetMonitorReport() {this.pageLoading = falseGetMonitorReport().then(res => {if (res.status) {let data = res.data;if (data) {this.option = {url: data.fileViewPath,fileType: data.fileType,title: "",isEdit: false,}}this.pageLoading = true}})}}}
</script>
<style lang="less" scoped>.monitor-report {.up-class {margin-bottom: 10px;}.office {height: 100vh;}}
</style>
2)查看
通过文件id请求查看文件
export function handleDocType(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 = 'text'}if (fileTypesCsv.includes(fileType)) {docType = 'spreadsheet'}if (fileTypesPPt.includes(fileType)) {docType = 'presentation'}return docType;
}
============================================
html集成首先实现前端预览功能:
<div id="fileEdit"></div>
// 页面引入document的api.js
<script type="text/javascript" src="http://localhost:9090/web-apps/apps/api/documents/api.js"></script>
// 调用js创建预览对象
new DocsAPI.DocEditor("fileEdit", // 元素id{"document": {"permissions": {"edit": true,},"fileType": "docx", // 展示文件的类型"title": "页面展示的文件名称","url":"下载文件的接口" //读取文件进行展示},"documentType": "text","editorConfig": {"lang" : "zh-CN",// 回调接口,用于编辑后实现保存的功能,(关闭页面5秒左右会触发)"callbackUrl": "保存文件的接口?path=告诉保存接口需要覆盖的文件"},"height": "1000px","width": "100%"})
1.我们在config配置了callbackUrl,文档加载时会调用这个接口,此时status = 1,我们给onlyoffice的服务返回{"error":"0"}的信息,这样onlyoffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
The document could not be saved. Please check connection settings or contact your administrator.
When you click the 'OK' button, you will be prompted to download the document.
Find more information about connecting Document Server当我们关闭编辑窗口后,十秒钟左右onlyoffice会将它存储的我们的编辑后的文件,,此时status = 2,通过request发给我们,我们需要做的就是接收到文件然后回写该文件。tips:回调接口中要给唯一标识,让程序知道要回写的文件;2.post接口
后端保存接口@ApiOperation(value = "文档保存")@RequestMapping(value = "/docx/save",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")@ResponseBodypublic void saveWord(HttpServletRequest request, HttpServletResponse response) {try {PrintWriter writer = response.getWriter();String body = "";try{Scanner scanner = new Scanner(request.getInputStream());scanner.useDelimiter("\\A");body = scanner.hasNext() ? scanner.next() : "";scanner.close();}catch (Exception ex){writer.write("get request.getInputStream error:" + ex.getMessage());return;}if (body.isEmpty()){writer.write("empty request.getInputStream");return;}JSONObject jsonObj = JSON.parseObject(body);int status = (Integer) jsonObj.get("status");int saved = 0;if(status == 2 || status == 3)//MustSave, Corrupted{String downloadUri = (String) jsonObj.get("url");try{URL url = new URL(downloadUri);java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();InputStream stream = connection.getInputStream();if (stream == null){throw new Exception("Stream is null");}// 从请求中获取要覆盖的文件参数定义"path"String path = request.getParameter("path");File savedFile = new File(path);try (FileOutputStream out = new FileOutputStream(savedFile)){int read;final byte[] bytes = new byte[1024];while ((read = stream.read(bytes)) != -1){out.write(bytes, 0, read);}out.flush();}connection.disconnect();}catch (Exception ex){saved = 1;ex.printStackTrace();}}System.out.print("编辑完成--------------11111");writer.write("{\"error\":" + saved + "}");} catch (IOException e) {e.printStackTrace();}}
demo下载:
https://download.csdn.net/download/qq_38567039/12915876