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就可以保存文件,预览效果如下

相关推荐
王磊鑫11 分钟前
重返JAVA之路——图书管理系统
java·开发语言
听闻风很好吃14 分钟前
Java设计模式之观察者模式:从入门到架构级实践
java·观察者模式·设计模式
艺杯羹16 分钟前
JDBC 初认识、速了解
java·数据库·jdbc
陵易居士17 分钟前
Spring如何解决项目中的循环依赖问题?
java·后端·spring
铁弹神侯25 分钟前
Maven相关名词及相关配置
java·maven
会飞的皮卡丘EI38 分钟前
关于Blade框架对数字类型的null值转为-1问题
java·spring boot
雷渊41 分钟前
如何保证数据库和Es的数据一致性?
java·后端·面试
fjkxyl42 分钟前
Spring的启动流程
java·后端·spring
极客先躯44 分钟前
高级java每日一道面试题-2025年4月06日-微服务篇[Nacos篇]-如何诊断和解决Nacos中的常见问题?
java·开发语言·微服务
东锋1.31 小时前
Spring AI 发布了它的 1.0.0 版本的第七个里程碑(M7)
java·人工智能·spring