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