启动一个documentServer的容器
docker run -it --name documentServer -d -p 9090:80 onlyoffice/documentserver
首先实现前端预览功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="placeholder"></div>
<script type="text/javascript" src="http://localhost:9090/web-apps/apps/api/documents/api.js"></script>
<script>
var docEditor = new DocsAPI.DocEditor("placeholder", {
"document": {
"fileType": "docx",
"permissions": {
"edit": false,
},
"key": "C8D7FB890BAC496FB0D27B163EDB88BDAA",
"title": "zf张飞.docx",
"url": "文件下载接口",
},
"height": "1000px",
"width": "100%"
});
</script>
</body>
</html>
- 我们在config配置了callbackUrl,文档加载时会调用这个接口,此时status = 1,我们给onlyoffice的服务返回{"error":"0"}的信息,这样onlyoffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
The document could not be saved. Please check connection settings or contact your administrator.
When you click the 'OK' button, you will be prompted to download the document.
Find more information about connecting Document Server
- 当我们关闭编辑窗口后,十秒钟左右onlyoffice会将它存储的我们的编辑后的文件,,此时status = 2,通过request发给我们,我们需要做的就是接收到文件然后回写该文件。
tips:回调接口中要给唯一标识,让程序知道要回写的文件;2.post接口
后端保存接口
@ApiOperation(value = "文档保存")
@RequestMapping(value = "/docx/save",
method = RequestMethod.POST,
produces = "application/json;charset=UTF-8")
@ResponseBody
public void saveWord(HttpServletRequest request, HttpServletResponse response) {
try {
PrintWriter writer = response.getWriter();
String body = "";
try
{
Scanner scanner = new Scanner(request.getInputStream());
scanner.useDelimiter("\\A");
body = scanner.hasNext() ? scanner.next() : "";
scanner.close();
}
catch (Exception ex)
{
writer.write("get request.getInputStream error:" + ex.getMessage());
return;
}
if (body.isEmpty())
{
writer.write("empty request.getInputStream");
return;
}
JSONObject jsonObj = JSON.parseObject(body);
int status = (Integer) jsonObj.get("status");
int saved = 0;
if(status == 2 || status == 3)//MustSave, Corrupted
{
String downloadUri = (String) jsonObj.get("url");
try
{
URL url = new URL(downloadUri);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
if (stream == null)
{
throw new Exception("Stream is null");
}
// 从请求中获取要覆盖的文件参数定义"path"
String path = request.getParameter("path");
File savedFile = new File(path);
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();
}
catch (Exception ex)
{
saved = 1;
ex.printStackTrace();
}
}
System.out.print("编辑完成--------------11111");
writer.write("{\"error\":" + saved + "}");
} catch (IOException e) {
e.printStackTrace();
}
}
原文链接:https://www.jianshu.com/p/262c3fc77f0c
网友评论