当前位置: 首页 > news >正文

onlyoffice 在线编辑集成

onlyoffice 在线编辑集成

项目中要使用word在线编辑功能,记录一下过程

安装使用docker版本

docker run -itd -p 8001:80 --name kodoffice --restart always registry.cn-hangzhou.aliyuncs.com/kodcloud/kodoffice:7.4.1.1

启动后http://192.168.x.x:8001/web/ 访问

html前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文档编辑</title>
    <script src="http://192.168.0.12:8001/web-apps/apps/api/documents/api.js"></script>
</head>
<body style="margin:0px;padding:0px;">
    <div id="placeholder" class = "nav" style="width:100%;height:100%;min-height:900px;"></div>
</body>
<script>
 
window.onmessage = function (event) {
	var data = event.data;
    //var data = JSON.parse(event.data);
    //console.log(data)
    if (data.event == "onDocumentStateChange" && data.data == false) {
    	console.log("保存成功");
    }
}
 
 
var fileInfo = ${fileInfo};
var fileid = "${fileid}";
var uuid = "${uuid}";
var suffix,fileName;
if(fileInfo) {
	suffix = fileInfo.suffix;
	fileName = fileInfo.fileName;
}
console.log(fileid,uuid,suffix,fileName,handleDocType(suffix))
function handleDocType(fileType) {
	  var docType = '';
	  var fileTypesDoc = [
	    'doc', 'docm', 'docx', 'dot', 'dotm', 'dotx', 'epub', 'fodt', 'htm', 'html', 'mht', 'odt', 'ott', 'pdf', 'rtf', 'txt', 'djvu', 'xps'
	  ];
	  var fileTypesCsv = [
	    'csv', 'fods', 'ods', 'ots', 'xls', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx'
	  ];
	  var 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;
	}
	
	var origin   = window.location.origin;
 
    new DocsAPI.DocEditor("placeholder", {
        "document": {
            "fileType": suffix, //文件类型
            "key": uuid, //文件key,确保唯一就行
            "title": fileName, //文件名称
            "url": origin+"/sysfile/download2?id="+fileid,
            "permissions": {
                "edit": true,
                "comment": true,
                "download": false,
                "fillForms": true,
                "print": true,
                "review": true
            },
        },
        "documentType": handleDocType(suffix), //word:docx,xlsx:cell
        "type": "desktop",
        "width": "100%",
        "height": "900px",
        "editorConfig": {
            "callbackUrl": origin+"/admin/onlyoffice/save?fileid="+fileid,
			"lang":"zh-CN",
			"customization":{
		        "forcesave":"true",
		        "download": "false",
		        "close": {
	                "visible": true,
	                "text": "Close file"
	            }
		    },
		    "mode":""//view
        },
        "token":""
    });
</script>
</html>

java后端代码

/**
	 * 
	 * 下载上传文件
	 * 
	 * @param request
	 * @param id
	 */
	@RequestMapping(path = "/download2")
	public void downloadFile2(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "id", required = true) String id) throws Exception {
		Long fileId = 0L;
		if (StrUtils.isEmpty(id)) {
			return;
		}
		fileId = StrUtils.parseLong(id);
		if (fileId <= 0L) {
			return;
		}
		
		SysFileEntity fileInfo = xxService.getFileListByid(fileId);
		if (fileInfo==null || StrUtils.isEmpty(fileInfo.getPath())) {
			writerHTML(response, "文件不存在");
			return;
		}
		String fileName =URLEncoder.encode(fileInfo.getFileName(), "UTF-8") ;
		String path = fileInfo.getPath();
		if (!path.startsWith("/")) {
			path =  uploadPath + "/" + path;
		} else {
			path = uploadPath + path;
		}
 
		File file = new File(path);
		if (!file.exists()) {
			writerHTML(response, "文件不存在");
			return;
		}
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
		response.setContentLength((int) file.length());
		// 创建输入流和输出流
		try {
			FileInputStream in = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			byte[] buffer = new byte[4096];
			int bytesRead;
			// 读取文件并写入响应
			while ((bytesRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件不存在.");
		}
	}
 
	private void writerHTML(HttpServletResponse response, String html) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		try {
			response.getWriter().print(html);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
 
@Controller
@RequestMapping("/admin")
public class OnlyofficeController {
	
	@Value("${bsj.uploadPath}")
	private String uploadPath;
	
	@Autowired
	private FilePreviewService filePreviewService;
	
	@GetMapping("/onlyoffice/edit")
	public String edit(Model model,HttpServletRequest request) {
		Long fileid = StrUtils.parseLong(request.getParameter("fileid"));
		SysFileEntity fileInfo = filePreviewService.getFileListByid(fileid);
		request.setAttribute("fileid", fileid+"");
		request.setAttribute("uuid", UUID.fastUUID());
		request.setAttribute("fileInfo",JSONObject.toJSONString(fileInfo));
		return "document";
	}
	
	
	@PostMapping(value = "/onlyoffice/save")
	@ResponseBody
	public String onlyOfficeCallBack(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("RemoteAddr----"+request.getRemoteAddr());//client's IP address from the remote host
		System.out.println("User-Agent----"+request.getHeader("User-Agent"));
		Long fileid = StrUtils.parseLong(request.getParameter("fileid"));
		Scanner scanner;
	    try {
	        scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
	        String body = scanner.hasNext() ? scanner.next() : "";
	        JSONObject jsonObject = JSONObject.parseObject(body);
	        Integer status = jsonObject.getInteger("status");
	        System.out.println("status----->"+status);
	        if (status == 2 || status == 3 || status == 6) {//6=强制保存
	            String downloadUri = jsonObject.getString("url");
	            URL url = new URL(downloadUri);
	            HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
	            InputStream stream = connection.getInputStream();
	            //查询附件信息,以获取附件存储路径
	            SysFileEntity fileInfo = filePreviewService.getFileListByid(fileid);
	    		String path = fileInfo.getPath();
	    		if (!path.startsWith("/")) {
	    			path =  uploadPath + "/" + path;
	    		} else {
	    			path = uploadPath + path;
	    		}
	    		System.out.println("保存文件-->"+path);
	    		File savedFile = new File(path);
	    		if (!savedFile.exists()) {
	    			return  "{\"error\":-1}";
	    		}
	            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();
	        }
	        return  "{\"error\":0}";
	    } catch (IOException e) {
	    	return  "{\"error\":-1}";
	    }
	    
	}
 
 
 
	
}

ctrl+s就可以保存文件,预览效果如下
## 标题

相关文章:

  • 【数据结构_8】栈和队列
  • Java基础——面试自我总结
  • Linux基础IO(七)之理解文件系统
  • 文心一言开发指南03——千帆大模型平台产品优势
  • 力扣每日打卡 3396. 使数组元素互不相同所需的最少操作次数(简单)
  • 【NLP】 22. NLP 现代教程:Transformer的训练与应用全景解读
  • 高速电路中的电阻、电容的选型及应用
  • SCP-Firmware安全通告:CVE-2024-11863和CVE-2024-11864
  • 数组中的第K个最大元素
  • 运行便携软件提示系统从服务器返回一个参照问题解决
  • CVE重要漏洞复现-Fastjson1.2.24-RCE漏洞
  • 一键部署ai画图环境foooocus colab
  • c++------模板进阶
  • 计算机组成原理 第 1 章 概 论
  • C++基础系列【36】异常处理
  • 系统设计模块之安全架构设计(身份认证与授权(OAuth2.0、JWT、RBAC/ABAC))
  • 使用WindSurf生成贪吃蛇小游戏:从零开始的开发之旅
  • websoket 学习笔记
  • 【LLM】A2A 与 MCP:剖析 AI Agent 互联时代的两种关键协议
  • 路由引入配置
  • 五一出游火爆!热门线路抢票难度堪比春运,有热门目的地酒店价格涨近4倍
  • 人民日报聚焦外贸“重镇”福建晋江:多元化布局扩大“朋友圈”
  • 著名电化学家、我国工业电化学奠基人之一郭鹤桐逝世
  • “万人大院”重组,上海交大校长丁奎岭:人才培养事关生存发展,再难也要改
  • 对话地铁读书人|来自大学教授的科普:读书日也是版权日
  • 青创上海—2025浦东徒步行活动举行,“青年草坪创新创业湃对”正式亮相