Logo

office online server实现文档的预览编辑

photo

2022年03月03日

最近项目中需要用到office文件在线编辑功能,然而很多解决方案都是收费的,于是决定采用微软免费的microsoft office online 2016和wopi 协议来实现。

wopi 协议

WOPI的英文全称是“Web Application Open Platform Interface”,中文名为“Web应用程序开放平台接口协议”。WOPI协议提供一系列基于web方式的,使文档能在 Office Web Apps 中查看与编辑的接口服务。

只要 web 应用按照标准,实现了 WOPI 的接口,那么就可以调用 Office Web Apps,实现文档的在线预览编辑。比如 SharePoint,Exchange,SkyDriver,Dropbox 集成了 Office Web Apps。

在 WOPI 结构中,存放Office文档的 web 应用叫 WOPI Host 或者 WOPI Server。把查看编辑操作 Office 文档的 web 应用叫 WOPI Client 或者叫 WOPI applications。SharePoint,Exchange,自己开发的文档管理系统充当的就是 WOPI Host,Office Web Apps 充当的就是 WOPI Client 。

Office开发团队对WOPI的介绍:http://blogs.msdn.com/b/officedevdocs/archive/2013/03/21/introducing-wopi.aspx。
Office Web Apps服务器概述:http://technet.microsoft.com/en-us/library/jj219437.aspx。

开发环境

office online的安装教材网上很多,这里就不再赘述了。安装好office online,然后按照下面的步骤进行wopihost的开发。我用的开发环境是jkd1.8,spring boot。

我们需要实现3个接口
GET api/wopi/files/{name}
GET api/wopi/files/{name}/contents
POST api/wopi/files/{name}/contents

其中第一个接口获取文件的信息,返回的是json数据格式,第二个是获取文件流,第三个是保存修改文件。

接口实现

先看下获取文信息接口的实现:

@GetMapping("/files/{name}")
public void getFileInfo(HttpServletRequest request, HttpServletResponse response) {
    String uri = request.getRequestURI();
    FileInfo info = new FileInfo();

    try  {
        // 获取文件名, 防止中文文件名乱码
        String fileName = URLDecoder.decode(uri.substring(uri.indexOf("wopi/files/") + 11), CHARSET_UTF8);
        if (fileName != null && fileName.length() > 0) {
            File file = new File(filePath + fileName);
            if (file.exists()) {
                info.setBaseFileName(file.getName());
                info.setSize(file.length());
                info.setOwnerId("admin");
                info.setVersion(file.lastModified());
                info.setSha256(getHash256(file));
            }
        }

        ObjectMapper mapper = new ObjectMapper();
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(mapper.writeValueAsString(info));
    } catch (Exception e) {
        logger.error("getFileInfo failed, errMsg: {}", e.toString());
        e.printStackTrace();
    }
}

然后是获取文件流接口的实现:

@GetMapping("/files/{name}/contents")
public void getFile(@PathVariable String name, HttpServletResponse response) {
    // 文件的路径
    String path = filePath + name;
    File file = new File(path);
    String filename = file.getName();

    try (InputStream fis = new BufferedInputStream(new FileInputStream(path));
         OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        // 清空response
        response.reset();

        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" +
                new String(filename.getBytes(CHARSET_UTF8), "ISO-8859-1"));
        response.addHeader("Content-Length", String.valueOf(file.length()));

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        toClient.write(buffer);
        toClient.flush();
    } catch (IOException e) {
        logger.error("getFile failed, errMsg: {}", e.toString());
        e.printStackTrace();
    }
}

保存文件修改的接口实现:

@PostMapping("/files/{name}/contents")
public void postFile(@PathVariable(name = "name") String name, @RequestBody byte[] content) {
    // 文件的路径
    String path = filePath + name;
    File file = new File(path);

    try (FileOutputStream fop = new FileOutputStream(file)) {
        fop.write(content);
        fop.flush();
    } catch (IOException e) {
        logger.error("postFile failed, errMsg: {}", e.toString());
        e.printStackTrace();
    }
}

###接口访问

访问http://owas.contoso.com/hosting/discovery,owas.contoso.com是配置的office online的域名,当然也可以通过IP访问,请换成自己的地址,如图:
这里写图片描述

在上面可以找到对应的文件类型的请求路径。然根据上面的URL+ WOPISrc=wopiHost的接口地址
就可以实现服务了。

例如word文档预览
http://[owas.domain]/wv/wordviewerframe.aspx?WOPISrc=http://[WopiHost.domain]:8080/wopi/files/test.docx
这里写图片描述

word文档编辑
http://[owas.domain]/we/wordeditorframe.aspx?WOPISrc=http://[WopiHost.domain]:8080/wopi/files/test.docx
这里写图片描述

代码已上传github,有用的话记得start一下啊__
地址 https://github.com/ethendev/wopihost

注意:web app上没有保存按钮,是自动保存的


参考资料
Office Online Server 概述
部署 Office Online Server
Windows Server 2012 R2 创建AD域
WOPI协议信息

Office Online Server下载地址
可以从批量许可服务中心 (VLSC) 下载 Office Online Server。
备用下载地址:http://www.0daydown.com/10/630107.html。

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
本文为原创文章,请注意保留出处!

标签:js缘起最近在做一个活动需求,需求交互有跨项目,跳转到另一个项目里完成指定任务,再回来领...切换浏览器tab刷新实现

热门文章

西游记之大圣归来 《西游记之大圣归来》是根据中国传统神话故事《西游记》进行拓展和演绎的3D动画电影。由横店影视、天空之城、燕城十月与微影时代作为出品方,高路动画、恭梓兄弟、世纪长龙、山东影视、东台龙行盛世、淮安西游产业与永康壹禾作为联合出品方出品,田晓鹏执导,张磊、林子杰、刘九容和童自荣等联袂配音。影片讲述了已于五行山下寂寞沉潜五百年的孙悟空被儿时的唐僧——俗名江流儿的小和尚误打误撞地解除了封印,在相互陪伴的冒险之旅中找回初心,完成自我救赎的故事。 作者:Pastore Antonio
1448 浏览量
常用的Centos操作Shell命令 玩WordPress的时候经常会接触到一些常用的命令,老是忘记……人年纪大了就是不给力啊。浏览量:...常用的Centos操作Shell命令 作者:Pastore Antonio
1387 浏览量
ffmpeg+srs 实现直播流 这篇文章是我在做直播流的时候收集的所有素材,没有太多的整理,都放到了脑袋里面了,之后有时间了再整理成...ffmpeg+srs实现直播流 作者:Pastore Antonio
1387 浏览量
项目十大管理和五大过程 PMBOK五大过程组是什么?PMBOK五大过程组是:启动过程、规划过程、执行过程、监...项目十大管理和五大过程 作者:Pastore Antonio
1363 浏览量
[ Office 365 开发系列 ] 身份认证 前言本文完全原创,转载请说明出处,希望对大家有用。通常我们在开发一个应用时,需要考虑用户身份认证...[Office365开发系列]身份认证 作者:Pastore Antonio
1357 浏览量