启动一个documentServer的容器
docker run -it --name documentServer -d -p 9090:80 onlyoffice/documentserver
复制代码
- 使得可以访问http://localhost:9090/web-apps/apps/api/documents/api.js
首先实现前端预览功能
<div id="fileEdit"></div>
// 页面引入document的api.js
<script type="text/javascript" src="http://localhost:9090/web-apps/apps/api/documents/api.js"></script>
// 调用js创建预览对象
new DocsAPI.DocEditor("fileEdit", // 元素id
{
"document": {
"permissions": {
"edit": true,
},
"fileType": "docx", // 展示文件的类型
"title": "页面展示的文件名称",
"url":"下载文件的接口" //读取文件进行展示
},
"documentType": "text",
"editorConfig": {
"lang" : "zh-CN",
// 回调接口,用于编辑后实现保存的功能,(关闭页面5秒左右会触发)
"callbackUrl": "保存文件的接口?path=告诉保存接口需要覆盖的文件"
},
"height": "1000px",
"width": "100%"
})
复制代码
- 我们在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();
}
}
复制代码
原文链接:www.jianshu.com/p/262c3fc77…
所有评论(0)