摘要

在一些项目中需要在线预览office文档,包括word,excel,ppt等。达到预览文档的目的有很多方法,可以看我之前总结,在线预览的n种方案:

[Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有真相,总有一款适合你!

,由于客户那里有安装web office apps服务,调用该服务就可以实现文档的在线预览,所以在项目中就采用了这种方式,下面列出了实践步骤。

步骤

定义文件信息:

该信息用来调用web office apps服务回调查找文件信息时用到。

    public class CheckFileInfo
{
public CheckFileInfo(); public string BaseFileName { get; set; }
public string OwnerId { get; set; }
public long Size { get; set; }
public string SHA256 { get; set; }
public string Version { get; set; }
}

获取文件信息的接口

    public interface IFileHelper
{
Task<CheckFileInfo> GetFileInfo(string fileMD5);
Task<string> GetSHA256Async(string url);
string GetSHA256Async(byte[] buffer);
}

接口实现

   public class FileHelper : IFileHelper
{
FileBusiness _FileBusiness;
public FileHelper()
{
_FileBusiness = new FileBusiness();
}
/// <summary>
/// 获取文件信息
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public async Task<CheckFileInfo> GetFileInfo(string fileMD5)
{
var fileInfo = _FileBusiness.FindFileByMD5(fileMD5);
if (fileInfo != null)
{
var rv = new CheckFileInfo
{
Version = DateTime.Now.ToString("s"),
Size = Convert.ToInt64(fileInfo.FileSize),
OwnerId = fileInfo.Itcode,
BaseFileName = fileInfo.FileName,
SHA256 = fileInfo.SHA256
};
if (string.IsNullOrEmpty(fileInfo.SHA256))
{
rv.SHA256 = await GetSHA256Async(fileInfo.Url);
fileInfo.SHA256 = rv.SHA256;
await _FileBusiness.UpldateAsyncByUrl(fileInfo);
}
return rv;
}
else
{
return null;
}
}
public async Task<string> GetSHA256Async(string url)
{
string sha256 = string.Empty;
using (var sha = SHA256.Create())
{
WebClient webClient = new WebClient();
byte[] buffer = await webClient.DownloadDataTaskAsync(url);
byte[] checksum = sha.ComputeHash(buffer);
sha256 = Convert.ToBase64String(checksum);
}
return sha256;
} public string GetSHA256Async(byte[] buffer)
{
string sha256 = string.Empty;
using (var sha = SHA256.Create())
{
WebClient webClient = new WebClient();
byte[] checksum = sha.ComputeHash(buffer);
sha256 = Convert.ToBase64String(checksum);
}
return sha256;
}
}

这里用到了文件分布式存储,要预览的放在了另外的文件服务器上面,所以这里使用webclient下载,获取到文件信息,保存在数据库中,如果存在则直接返回。当然,你可以使用FileStream来读取文件的响应信息。

获取文件预览的地址

根据web office apps服务的地址,文件扩展名获取预览的link

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>
/// <returns></returns>
public string GetDocumentLink(string fileMD5, string ext)
{
string apiUrl = string.Format(ConfigManager.OWA_MY_VIEW_URL, fileMD5);
return string.Format("{0}{1}{2}&access_token={3}", ConfigManager.OWA_URL, FindUrlByExtenstion(ext), apiUrl, fileMD5);
}
/// <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(".") >= )
{
//如果包含.则进行过滤
ext = ext.TrimStart('.');
}
Dictionary<string, string> dic = new Dictionary<string, string>()
{
{"ods","/x/_layouts/xlviewerinternal.aspx?WOPISrc="},
{"xls", "/x/_layouts/xlviewerinternal.aspx?WOPISrc="},
{"xlsb", "/x/_layouts/xlviewerinternal.aspx?WOPISrc="},
{"xlsm", "/x/_layouts/xlviewerinternal.aspx?WOPISrc="},
{"xlsx", "/x/_layouts/xlviewerinternal.aspx?WOPISrc="},
{"one", "/o/onenoteframe.aspx?WOPISrc="},
{"onetoc2", "/o/onenoteframe.aspx?WOPISrc="},
{"odp", "/p/PowerPointFrame.aspx?WOPISrc="},
{"pot", "/p/PowerPointFrame.aspx?WOPISrc="},
{"potm", "/p/PowerPointFrame.aspx?WOPISrc="},
{"potx", "/p/PowerPointFrame.aspx?WOPISrc="},
{"pps", "/p/PowerPointFrame.aspx?WOPISrc="},
{"ppsm", "/p/PowerPointFrame.aspx?WOPISrc="},
{"ppsx", "/p/PowerPointFrame.aspx?WOPISrc="},
{"ppt", "/p/PowerPointFrame.aspx?WOPISrc="},
{"pptm", "/p/PowerPointFrame.aspx?WOPISrc="},
{"pptx", "/p/PowerPointFrame.aspx?WOPISrc="},
{"doc", "/wv/wordviewerframe.aspx?WOPISrc="},
{"docm", "/wv/wordviewerframe.aspx?WOPISrc="},
{"docx", "/wv/wordviewerframe.aspx?WOPISrc="},
{"dot", "/wv/wordviewerframe.aspx?WOPISrc="},
{"dotm", "/wv/wordviewerframe.aspx?WOPISrc="},
{"dotx", "/wv/wordviewerframe.aspx?WOPISrc="},
{"pdf", "/wv/wordviewerframe.aspx?WOPISrc="}
};
return dic[ext];
}
}
}

web office apps 预览接口回调使用的api时,需要注意尽量传递id之类,如果传递name,文件名涉及到了中文,会有编码的问题,所以我这里传递的是文件的md5值。

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
{
/// <summary>
/// Primary class for WOPI interface. Supporting the 2 minimal API calls
/// requred for base level View
/// </summary>
public class FilesController : ApiController
{
IFileHelper _fileHelper;
HttpResponseMessage _response;
/// <summary>
/// Base constructor
/// </summary>
public FilesController()
{
_fileHelper = new FileHelper();
_response = new HttpResponseMessage(HttpStatusCode.Accepted);
//允许哪些url可以跨域请求到本域
_response.Headers.Add("Access-Control-Allow-Origin", "*");
//允许的请求方法,一般是GET,POST,PUT,DELETE,OPTIONS
_response.Headers.Add("Access-Control-Allow-Methods", "POST");
//允许哪些请求头可以跨域
_response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type");
}
/// <summary>
/// Required for WOPI interface - on initial view
/// </summary>
/// <param name="name">file name</param>
/// <returns></returns>
public async Task<CheckFileInfo> Get(string name)
{
return await _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>
public async Task<CheckFileInfo> Get(string name, string access_token)
{
return await _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>
public async Task<HttpResponseMessage> GetFile(string name, string access_token)
{
try
{
_response.StatusCode = HttpStatusCode.OK;
FileBusiness FileBusiness = new FileBusiness();
var file = FileBusiness.FindFileByMD5(name);
if (file != null)
{
WebClient webClient = new WebClient();
byte[] buffer = await webClient.DownloadDataTaskAsync(file.Url);
MemoryStream stream = new MemoryStream(buffer);
_response.Content = new StreamContent(stream);
_response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
return _response;
}
catch (Exception ex)
{
_response.StatusCode = HttpStatusCode.InternalServerError;
var stream = new MemoryStream(UTF8Encoding.Default.GetBytes(ex.Message ?? ""));
_response.Content = new StreamContent(stream);
return _response;
}
}
}
}

路由配置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http; namespace WebSite.OfficeViewerService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// Web API 路由
config.Routes.MapHttpRoute(
name: "Contents",
routeTemplate: "api/wopi/files/{name}/contents",
defaults: new { controller = "files", action = "GetFile" }
);
config.Routes.MapHttpRoute(
name: "FileInfo",
routeTemplate: "api/wopi/files/{name}",
defaults: new { controller = "Files", action = "Get" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Files", id = RouteParameter.Optional }
);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Mvc;
using WebSite.OfficeViewerService.Helpers; namespace WebSite.OfficeViewerService.Controllers
{
public class HomeController : Controller
{
IFileHelper _fileHelper = new FileHelper();
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Viewer(string url, string name)
{
string itcode = string.Empty;
try
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("Sorry,Url is errr,the file is not found");
}
string fileExt = url.Substring(url.LastIndexOf('.'));
WopiAppHelper wopiHelper = new WopiAppHelper();
FileBusiness FileBusiness = new FileBusiness();
var file = FileBusiness.FindFileByUrl(url);
string fileMD5 = string.Empty;
if (file == null)
{
WebClient webClient = new WebClient();
byte[] buffer = await webClient.DownloadDataTaskAsync(url);
fileMD5 = MD5Helper.GetMD5FromFile(buffer);string sha256 = _fileHelper.GetSHA256Async(buffer);
await fastDFSFileBusiness.SaveAsync(new FastDFSFile
{
Dt = DateTime.Now,
FileMd5 = fileMD5,
FileName = name,
FileSize = buffer.Length,
Itcode = itcode,
Url = url,
SHA256 = sha256
});
}
else
{
fileMD5 = file.FileMd5;
}
var result = wopiHelper.GetDocumentLink(fileMD5, fileExt);
return Redirect(result);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return View();
}
}
}

包装预览接口,其它应用通过传递文件的url和文件名称,然后跳转到实际的预览界面。简单粗暴,不用每个应用都在实现上面的方法。

web office apps 在线预览实践的更多相关文章

  1. office文件在线预览,模仿网易邮箱在线预览的

    最近研究了半天,代码是倾情奉送啊,C#,asp.net的 这个原理是office文件转换为PDF文件,然后再转换成SWF文件,FlexPaper+swfTools. 有个问题,需要在web.confi ...

  2. WEB文档在线预览解决方案

    web页面无法支持预览office文档,但是却可以预览PDF.flash文档,所以大多数解决方案都是在服务端将office文档转换为pdf,然后再通过js的pdf预览插件(谷歌浏览器等已经原生支持嵌入 ...

  3. 【Java】web实现图片在线预览

    一.场景还原 用户上传了一张图片,已有服务器保存路径,现由于系统配置无法直接通过图片URL打开预览图片,需实现点击预览将图片显示在浏览器上. 二.实现方法 html: <a href=" ...

  4. office online在线预览服务与https的tls证书兼容问题

    问题现象:k8s环境配置证书后,无法调用office online 服务,附件无法预览 问题原因:ingress默认启用得是tls1.2,不兼容以下版本 k8s环境解决方法:增加ingress配置,兼 ...

  5. 推荐个office能在线预览的插件

    1.chrome  office viewer 这个可以离线使用 2.微软 office web app  可以使用微软在线服务器或则自己搭建服务器 有兴趣的朋友百度一下具体操作方法

  6. 在线预览office文件

    Office Online 实现在线预览 office的在线预览,针对不同的浏览器版本和系统具有要求,具体的相关文档请参考官方文档. 利用office online 平台进行office 文档的在线查 ...

  7. 在线预览Office文件【效果类似百度文库】

    引言 结合上个项目和目前做的这个项目,其中都用到了Office文件在线预览,目前项目中是用到公司购买的Ntko控件,该控件每次浏览文件时则会提示安装信任插件,很繁琐,而且浏览效果不好. 提到Offic ...

  8. 在线预览Office文件【效果类似百度文库】(转载)

    转载地址:http://www.cnblogs.com/sword-successful/p/4031823.html 引言 结合上个项目和目前做的这个项目,其中都用到了Office文件在线预览,目前 ...

  9. JAVAWeb项目实现在线预览、打开office文件

    Web项目实现在线预览浏览word.ppt.excel文档方法 调用以下链接 https://view.officeapps.live.com/op/view.aspx?src=你的文档绝对路径 这里 ...

随机推荐

  1. Linux入门(二)Shell基本命令

    上一篇讲了普通用户切换到root用户,今天补充一点,对于Debian和Ubuntu用户,安装时候只有一个普通用户注册,在需要root权限时,我们可以在普通用户模式下输入sudo这个命令运行某些相关特权 ...

  2. git —— pycharm+git管理/编辑项目

    pycharm+git  管理/编辑项目 一.pycharm中配置github 二.配置git 并不是配置了GitHub就可以的.还需要配置一下Git 前提是本地中已经安装了git 三.把本地项目上传 ...

  3. Codeforces 429B Working out(递推DP)

    题目链接:http://codeforces.com/problemset/problem/429/B 题目大意:两个人(假设为A,B),打算健身,有N行M列个房间,每个房间能消耗Map[i][j]的 ...

  4. python2.7

    python2.7支持win32.win64 下载地址:http://pan.baidu.com/s/1dE39eQ9 初学,附一个牛人的python教程地址:http://www.liaoxuefe ...

  5. 转58同城 mysql规范

    这里面都是一些很简单的规则,看似没有特别大的意义,但真实的不就是这么简单繁杂的工作吗? 军规适用场景:并发量大.数据量大的互联网业务 军规:介绍内容 解读:讲解原因,解读比军规更重要 一.基础规范 ( ...

  6. 第六届CCF软件能力认证

    1.数位之和 问题描述 给定一个十进制整数n,输出n的各位数字之和. 输入格式 输入一个整数n. 输出格式 输出一个整数,表示答案. 样例输入 20151220 样例输出 13 样例说明 201512 ...

  7. 《精通Python设计模式》学习结构型之装饰器模式

    这只是实现了Python的装饰器模式. 其实,python的原生的装饰器的应用比这个要强,要广的. ''' known = {0:0, 1:1} def fibonacci(n): assert(n ...

  8. CCF CSP 201409-3 字符串匹配

    CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF CSP 201409-3 字符串匹配 问题描述 给出一个字符串和多行文字,在这些文字中找到字符串出现的那 ...

  9. NetworkX 使用(三)

    官方教程 博客:NetworkX NetworkX 使用(二) Introduction to Graph Analysis with NetworkX %pylab inline import ne ...

  10. Java_正则表达式&时间日期

    正则表达式 1.概念 正则表达式(英语:Regular Expression,在代码中常简写为regex). 正则表达式是一个字符串,使用单个字符串来描述.用来定义匹配规则,匹配一系列符合某个句法规则 ...