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前端代码

csharp 复制代码
<!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后端代码

csharp 复制代码
/**
	 * 
	 * 下载上传文件
	 * 
	 * @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就可以保存文件,预览效果如下

相关推荐
摇滚侠17 分钟前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
keep one's resolveY40 分钟前
SpringBoot实现重试机制的四种方案
java·spring boot·后端
天空属于哈夫克31 小时前
企业微信API常见的错误和解决方案
java·数据库·企业微信
摇滚侠2 小时前
VMvare 虚拟机 Oracle19c 安装步骤,远程连接 Oracle19c,百度网盘安装包
java·oracle
梁萌2 小时前
idea报错找不到XX包的解决方法
java·intellij-idea·启动报错·缺少包
Agent产品评测局2 小时前
生产排期与MES/ERP系统打通,实操方法详解 —— 2026企业级智能体自动化选型与实战指南
java·运维·人工智能·ai·chatgpt·自动化
阿丰资源3 小时前
基于Spring Boot的电影城管理系统(直接运行)
java·spring boot·后端
呱牛do it3 小时前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 8)
java
消失的旧时光-19434 小时前
Spring Boot 工程化进阶:统一返回 + 全局异常 + AOP 通用工具包
java·spring boot·后端·aop·自定义注解
NE_STOP4 小时前
Redis--发布订阅命令和Redis事务
java