摘要

在使用office web apps实现office文档在线预览的时候,需要注意的地方。

web api

web api作为owa在线预览服务回调的接口,这里面核心代码片段如下:

using H5.Business;
using H5.Business.Log;
using H5.Enums;
using H5.Model;
using H5.Utility;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;
using WebSite.OfficeViewerService.Helpers;namespace WebSite.OfficeViewerService.Controllers.Api
{[RoutePrefix("api/wopi")]public class FilesController : ApiController{IFileHelper _fileHelper;HttpResponseMessage _response;ILog _log;/// <summary>/// Base constructor/// </summary>public FilesController(){_fileHelper = new FileHelper();_response = new HttpResponseMessage(HttpStatusCode.OK);_log = new DbLog(LogSource.WebLog, AppNameType.office_view);}/// <summary>/// Required for WOPI interface - on initial view/// </summary>/// <param name="name">file name</param>/// <returns></returns>
        [HttpGet][Route("files/{name}")]public CheckFileInfo Get(string name){_log.Info(new LogModel { Content = "get fileinfo by name", Op = "get_fileinfo" });return _fileHelper.GetFileInfo(name);}/// <summary>/// Required for WOPI interface - on initial view/// </summary>/// <param name="name">file name</param>/// <param name="access_token">token that WOPI server will know</param>/// <returns></returns>
        [HttpGet][Route("files/{name}")]public CheckFileInfo Get(string name, string access_token){_log.Info(new LogModel { Content = "get fileinfo by name&access_token", Op = "get_fileinfo" });return _fileHelper.GetFileInfo(name);}/// <summary>/// Required for View WOPI interface - returns stream of document./// </summary>/// <param name="name">file name</param>/// <param name="access_token">token that WOPI server will know</param>/// <returns></returns>
        [HttpGet][Route("files/{name}/contents")]public HttpResponseMessage GetFile(string name, string access_token){_log.Info(new LogModel { Content = "get file contents by name&access_token", Op = "get_fileinfo" });return DownLoadFileStream(name, access_token);}/// <summary>/// get owa file/// </summary>/// <param name="name"></param>/// <returns></returns>
        [HttpGet][Route("files/{name}/contents")]public HttpResponseMessage GetFile(string name){_log.Info(new LogModel { Content = "get file contents by name", Op = "get_fileinfo" });return DownLoadFileStream(name, string.Empty);}private HttpResponseMessage DownLoadFileStream(string name, string access_token){try{_log.InfoAsync(new LogModel { Content = name + "_" + access_token, Itcode = string.Empty, Op = "Office_View_GetFile" });              FastDFSFileBusiness fastDFSFileBusiness = new FastDFSFileBusiness();var file = fastDFSFileBusiness.FindFastDFSFileByMD5(name);if (file != null){using (WebClient webClient = new WebClient()){byte[] buffer = webClient.DownloadData(file.Url);_log.Info(new LogModel { Content = "download file success", Op = "get_fileinfo" });MemoryStream stream = new MemoryStream(buffer);_response.Content = new StreamContent(stream);_response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");}}return _response;}catch (Exception ex){_log.Error(new LogModel { Ex = ex, Op = "Office_View_GetFile_err" });_response.StatusCode = HttpStatusCode.InternalServerError;var stream = new MemoryStream(UTF8Encoding.Default.GetBytes(ex.Message ?? ""));_response.Content = new StreamContent(stream);return _response;}}}
}

需要注意:在获取文件流的时候,不要是否文件流,不然会造成有的文件预览正常,有的预览报错。

fileHelper用来获取文件信息,这里文件统一上传到文件服务器fastdfs上,通过下载文件流设置文件信息,在传递文件的时候,使用文件md5进行传递,避免因为文件名出现中文名或者空格造成编码问题。

构造owa预览地址

using H5.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Serialization;namespace WebSite.OfficeViewerService.Helpers
{/// <summary>/// /// </summary>public class WopiAppHelper{public WopiAppHelper() { }/// <summary>/// 获取office在线预览的链接/// </summary>/// <param name="fileMD5"></param>/// <param name="ext"></param>/// <param name="fileUrl"></param>/// <returns></returns>public string GetDocumentLink(string fileMD5, string ext, string fileUrl){string apiUrl = string.Format(ConfigManager.OWA_MY_VIEW_URL, fileMD5);string findUrl = FindUrlByExtenstion(ext);if (!string.IsNullOrEmpty(findUrl)){return string.Format("{0}{1}{2}&access_token={3}", ConfigManager.OWA_URL, findUrl, apiUrl, fileMD5);}else{return fileUrl;}}/// <summary>/// 根据文件扩展名获取预览url/// </summary>/// <param name="ext"></param>/// <returns></returns>private string FindUrlByExtenstion(string ext){       if (string.IsNullOrEmpty(ext)){throw new ArgumentNullException("extension is empty.");}if (ext.IndexOf(".") >= 0){//如果包含.则进行过滤ext = ext.TrimStart('.').ToLower();}string url = string.Empty;switch (ext){case "ods":case "xls":case "xlsb":case "xlsm":case "xlsx":url = "/x/_layouts/xlviewerinternal.aspx?WOPISrc=";break;case "one":case "onetoc2":url = "/o/onenoteframe.aspx?WOPISrc=";break;case "odp":case "pot":case "potm":case "potx":case "pps":case "ppsm":              case "ppsx":case "ppt":case "pptm":case "pptx":url = "/p/PowerPointFrame.aspx?WOPISrc=";break;case "doc":case "docm":case "docx":case "dot":case "dotm":case "dotx":url = "/wv/wordviewerframe.aspx?WOPISrc=";break;default:break;}return url;}}
}

总结

在开发中因为涉及到回调,最好找一个代理的工具,比如ngrok将机器代理到外网,方便调试开发。

[Office Web Apps]实现在线office文档预览相关推荐

  1. 在线文件/文档预览/分页分片预览 之开源kkfileview(word转pdf,pdf截取,pdf转图片,Aspose jobConverter , OpenOffice ,libreoffice )

    前提说明 浏览器不能直接浏览word文件,但可以浏览pdf文件!!! 可以后台把word,excel 转成成pdf.然后给前端预览: 业界常用的开源工具有:Aspose jobConverter ,  ...

  2. office web apps java_整合Office Web Apps至自己的开发系统

    原文出处:http://www.cnblogs.com/poissonnotes/p/3267190.html 还可参考:https://www.cnblogs.com/majiang/p/36729 ...

  3. 在线文档预览方案-office web apps续篇

    上一篇在线文档预览方案-office web apps发布后收到很多网友的留言提问,所以准备再写一篇,一来介绍一下域控服务器安装,总结一下大家问的多的问题,二来宣传预览服务安装与技术支持的事情. 阅读 ...

  4. 在线文档预览方案-office web apps

    原文:在线文档预览方案-office web apps 最近在做项目时,要在手机端实现在线文档预览的功能.于是百度了一下实现方案,大致是将文档转换成pdf,然后在通过插件实现预览.这些方案没有具体实现 ...

  5. [转载]在线文档预览方案-Office Web Apps

    最近在做项目时,要在手机端实现在线文档预览的功能.于是百度了一下实现方案,大致是将文档转换成pdf,然后在通过插件实现预览.这些方案没有具体实现代码,也没有在线预览的地址,再加上项目时间紧迫.只能考虑 ...

  6. 用Ruby on Rails实现适应各种平台的在线Office文档预览

    前言 在许多Web应用中都需要预览文档的功能.而用户可能用不同的设备访问Web应用,可能是装有Windows系统的PC台式机,也有可能是iOS系统的iPad.一般来说,要预览的文档通常是主流的Offi ...

  7. 用 Ruby on Rails 实现适应各种平台的在线 Office 文档预览

    http://ruby-china.org/topics/17309 前言 在许多Web应用中都需要预览文档的功能.而用户可能用不同的设备访问Web应用,可能是装有Windows系统的PC台式机,也有 ...

  8. 跨平台Office文档预览原生插件,非腾讯X5,支持离线,稳定高可用

    引言 2023年4月13日零时起,腾讯浏览服务内核文档能力正式下线,要实现真正离线文档预览,于是有了这边文章. 前面写了多篇关于<跨平台文件在线预览解决方案>,不管使用pdf.js.Lib ...

  9. 文档预览 OfficeWebViewer:在浏览器中查看Office文档

    Office Web Viewer:在浏览器中查看Office文档 由办公室团队 即使您的读者没有安装Office,您的网站或博客上是否也有要阅读的Office文档?您宁愿先查看文档再下载吗?为了给您 ...

最新文章

  1. 【计算机网络】网络层 : IPv6 协议 ( IPv6 数据包格式 | IPv6 地址表示 | IPv6 地址类型 | IPv4 与 IPv6 协议对比 | IPv4 -> IPv6 过渡策略 )
  2. 文巾解题 695. 岛屿的最大面积
  3. Linux 下mysql5.7安装搬运 该安装说明坑最少
  4. JAVA软件图片浏览下载_java模拟浏览器下载图片
  5. 基于MaxCompute+PAI的用户增长方案实践
  6. linux mv 保持目录结构_(三)Linux系统目录结构
  7. BZOJ3597 SCOI2014方伯伯运椰子(分数规划+spfa)
  8. 分布式红锁的leaseTime的设计原理
  9. 解决Jenkins上git出现的“ERROR: Error fetching remote repo ‘origin‘”问题
  10. IDEA 日常小技巧
  11. Eclipse集成Git插件及使用
  12. Python实现图形学DDA算法
  13. Android系统终端命令大全
  14. dojo省份地市级联之地市Dao接口类(四)
  15. 计算机基础常见八股问题集合(含计算机网络,操作系统,计算机组成,数据结构与算法,数据库)
  16. Scrum敏捷开发框架
  17. 线性代数感悟之4 通过增广矩阵查看解的情况上篇
  18. 《元宇宙十大技术》感谢乔卫兵等6位为出版做出巨大贡献
  19. CDH集群安装OpenLDAP服务并集成sssd客户端
  20. 电压源与电流源的等效变换

热门文章

  1. 【渝粤题库】陕西师范大学151108 会计信息化 作业(高起专)
  2. android更新天气简单方法,简单教你如何编写Android天气预报小程序
  3. UVM field automation
  4. CodeForces 409C Magnum Opus
  5. Linux c语言 beep,用Beep()函数来实现c语言编写歌曲
  6. 前端 开关按钮样式_如何使用HTML5+css3制作出12种常用的按钮开关样式(附完整代码)...
  7. 精准测试新玩法の基于犯罪心理学挖掘代码风险
  8. 数据库原理与应用课程知识点
  9. 淘宝/天猫上传图片到淘宝 API 返回值说明(upload_img)
  10. “绿色低碳+数字孪生“双轮驱动,解码油气管道站升级难点 | 图扑软件