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

相关推荐
咖啡啡不加糖12 分钟前
RabbitMQ 消息队列:从入门到Spring Boot实战
java·spring boot·rabbitmq
玩代码19 分钟前
Java线程池原理概述
java·开发语言·线程池
NE_STOP22 分钟前
SpringBoot--如何给项目添加配置属性及读取属性
java
水果里面有苹果24 分钟前
20-C#构造函数--虚方法
java·前端·c#
%d%d228 分钟前
python 在运行时没有加载修改后的版本
java·服务器·python
金銀銅鐵34 分钟前
[Kotlin] 单例对象是如何实现的?
java·kotlin
泰勒疯狂展开35 分钟前
Java研学-MongoDB(三)
java·开发语言·mongodb
zzywxc78741 分钟前
AI技术通过提示词工程(Prompt Engineering)正在深度重塑职场生态和行业格局,这种变革不仅体现在效率提升,更在重构人机协作模式。
java·大数据·开发语言·人工智能·spring·重构·prompt
张先shen1 小时前
Elasticsearch RESTful API入门:索引的增删改查完全指南
java·大数据·elasticsearch·搜索引擎·架构·全文检索·restful
天天摸鱼的java工程师1 小时前
工作八年,如果现在让我重做“教务系统”毕业设计,我会这样答...
java·后端