微信或手机浏览器在线显示office文件(已測试ios、android)
近期开发微信企业号,发现微信andriod版内置浏览器在打开文件方面有问题,可是ios版没有问题。原因是ios版使用的是safari浏览器 支持文档直接打开。可是andriod版使用的是腾讯浏览器x5内核。不知道什么原因不支持。可能是集成出现的问题,这里提供解决方法。这样的方法也相同适用手机浏览器或者安卓开发。
通过此方法能够在微信上开发自己的第三方应用。或者解决自己的项目问题,解决方法及核心代码例如以下:
1、推断浏览器类型
HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//里面包括了设备类型
2、IOS版直接使用流输出
Andriod版利用openoffice+jod转换成html,然后对html内容又一次编辑。文件里有图片的将路径改为网络路径或者採用流输出(改成网络路径注意特殊符号,如+号会变成空格)
/**
* 从OA上抓取文件
* author 牟云飞
* company 海颐软件股份有限公司
* tel 15562579597
* qq 1147417467
* team 客服产品中心/于洋
* @return
*/
public String getFileFromOa(){ HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//里面包括了设备类型
if(-1!=userAgent.indexOf("iPhone")){
//-----------------//
//此方法须要浏览器自己可以打开。ios可以可是微信andriod版内置浏览器不支持
//-----------------//
//假设是苹果手机
//获得文件地址
String fileUrl = ServletActionContext.getRequest().getParameter("fileUrl");
fileUrl.replaceAll("%20", "\\+");//转换加号
String strURL = MessageUtil.oaUrl+fileUrl;
String fileType=strURL.substring(strURL.lastIndexOf(".")+1,strURL.length());
//获得图片的数据流
try {
URL oaUrl = new URL(strURL);
HttpURLConnection httpConn = (HttpURLConnection) oaUrl.openConnection();
InputStream in = httpConn.getInputStream();
//获取输出流
HttpServletResponse response = ServletActionContext.getResponse();
req.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=fileUrl.substring(fileUrl.lastIndexOf("/")+1, fileUrl.length()); response.setHeader("Content-Disposition",
"attachment;filename=" +
new String( (name ).getBytes(),
"iso-8859-1"));
if("doc".equals(fileType)||"docx".equals(fileType)){
response.setContentType("application/msword");
}else if("xls".equals(fileType)||"xlsx".equals(fileType)){
response.setContentType("application/msexcel");
}else{
response.setContentType("application/"+fileType);
}
OutputStream out = response.getOutputStream();
//输出图片信息
byte[] bytes = new byte[1024];
int cnt=0;
while ((cnt=in.read(bytes,0,bytes.length)) != -1) {
out.write(bytes, 0, cnt);
}
out.flush();
out.close();
in.close(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}else{
//假设非苹果手机。自己处理文档 //获得文件地址
String fileUrl = ServletActionContext.getRequest().getParameter("fileUrl"); fileUrl.replaceAll("%2B", "\\+");//转换加号
String strURL = MessageUtil.oaUrl+fileUrl;
//在本地存放OA文件,然后转换成html,再对文档中的图片路径进行改动,最后输出到页面
try {
URL oaUrl = new URL(strURL);
HttpURLConnection httpConn = (HttpURLConnection) oaUrl.openConnection();
InputStream in = httpConn.getInputStream();
//获取输出流
HttpServletResponse response = ServletActionContext.getResponse();
req.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=fileUrl.substring(fileUrl.lastIndexOf("/")+1, fileUrl.length()); //首先推断本地是否存在
String path=req.getRealPath("");
path=path.substring(0, path.lastIndexOf("\\")+1);
File htmlFile=new File(path + "OaFileToHtml\\"+name+".html");
if(!htmlFile.exists()){
//推断目录是否存在。创建目录
String oaFilePath=path + "OaFile";//存放OA文档的目录路径;
File oaFiles=new File(oaFilePath);
if(!oaFiles.exists()){
//假设目录不存在创建目录
oaFiles.mkdirs();
}
//将OA消息存入本地
File oafile=new File(oaFiles+ File.separator +name);
OutputStream out = new FileOutputStream(oafile);
//输出图片信息
byte[] bytes = new byte[1024];
int cnt=0;
while ((cnt=in.read(bytes,0,bytes.length)) != -1) {
out.write(bytes, 0, cnt);
}
out.flush();
out.close();
in.close();
//转换成html
String htmlFilePath =path + "OaFileToHtml";//OA文件转成html的位置
String htmlcontext=ConvertFileToHtml.toHtmlString(oafile, htmlFilePath);
req.setAttribute("htmlcontext", htmlcontext);
}else{
//已经存在转换成功的文档
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile),Charset.forName("gb2312")));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
//System.out.println("htmlStr=" + htmlStr);
// 返回经过清洁的html文本
req.setAttribute("htmlcontext", ConvertFileToHtml.clearFormat(htmlStr, ""));
} } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "lookfile";
} }
-------------------将word转换成html文件,并读取内容-------------------------
此类借鉴原地址并改动http://jadethao.iteye.com/blog/1817738
package com.haiyisoft.wx.util; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; /**
* * 端口启动命令:
* soffice -headless -accept="socket,port=8100;urp;
*
*
* author 牟云飞
* company 海颐软件股份有限公司
* tel 15562579597
* qq 1147417467
* team 客服产品中心/于洋
*
*/
public class ConvertFileToHtml {
/**
* 将word文档转换成html文档
* @param docFile 须要转换的word文档
* @param filepath 转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) { // 创建保存html的文件
String fileName=docFile.getName();
File htmlFile = new File(filepath + "/" + fileName + ".html");
// 创建Openoffice连接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 连接
con.connect();
} catch (ConnectException e) {
System.out.println("获取OpenOffice连接失败...");
e.printStackTrace();
} // 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 转换文档问html
converter.convert(docFile, htmlFile);
// 关闭openoffice连接
con.disconnect();
return htmlFile;
} /**
*
* 将word转换成html文件,而且获取html文件代码。
* @param docFile 须要转换的文档
* @param filepath 文档中图片的保存位置
* @return 转换成功的html代码
*/
public static String toHtmlString(File docFile, String filepath) {
// 转换word文档
File htmlFile = convert(docFile, filepath);
System.out.println(htmlFile.getAbsolutePath());
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile),Charset.forName("gb2312")));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
// 删除暂时文件
//htmlFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
//System.out.println("htmlStr=" + htmlStr);
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
} /**
*
* 清除一些不须要的html标记
*/ public static String clearFormat(String htmlStr, String docImgPath) { // 获取body内容的正则
String bodyReg = "<BODY .*</BODY>";
Pattern bodyPattern = Pattern.compile(bodyReg);
Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
if (bodyMatcher.find()) {
// 获取BODY内容,并转化BODY标签为DIV
htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV").replaceAll("</BODY>", "</DIV>");
} // 调整图片地址,这里将图片路径改为网络路径 htmlStr = htmlStr.replaceAll("<IMG SRC=\"../","<IMG SRC=\"" + MessageUtil.webUrl+"/******.do? action=***);
//特殊处理一下+号。由于网络传输+会变成空格。用%2B替换+号
String temp1=htmlStr.substring(htmlStr.indexOf("action=***"), htmlStr.length());
String temp2=temp1.substring(0,temp1.indexOf("."));
String temp3=temp2.replaceAll("\\+", "%2B");
htmlStr=htmlStr.substring(0,htmlStr.indexOf("action=***"))+temp3+temp1.substring(temp1.indexOf("."), temp1.length()); // 把<P></P>转换成</div></div>保留样式
// content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
// "<div$2</div>");
// 把<P></P>转换成</div></div>并删除样式
htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
// 删除不须要的标签
htmlStr = htmlStr.replaceAll("<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*? >","");
// 删除不须要的属性
htmlStr = htmlStr.replaceAll("<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>","<$1$2>"); return htmlStr; }
}
微信或手机浏览器在线显示office文件(已測试ios、android)的更多相关文章
- 在线显示office文件
微信或手机浏览器在线显示office文件 1.判断浏览器类型 HttpServletRequest req = ServletActionContext.getRequest(); String us ...
- laravel项目中手机浏览器在线阅读pdf文件-->PDFJS插件
第一步:下载链接:http://mozilla.github.io/pdf.js/getting_started/#download 第二步:将下载的文件放在项目中. 第三步:在项目中想要预览的地方给 ...
- openoffice+pdf2swf+FlexPaper在线显示office和pdf
前提:本人的系统为Ubuntu 13.10 64位系统.本篇是我在配置好环境后一段时间写的,所以操作上可能会有也错误,因此仅供参考. 搜索在线显示office和pdf,最常见的方法就是把都转为swf, ...
- 在线浏览office 文件
http://blog.csdn.net/binyao02123202/article/details/20051683 [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有 ...
- 织梦中在线显示pdf文件的方法
如何在织梦中添加pdf文件并显示呢?下面这个教程将带领大家来操作.(注:手机版无法查看) 第一步:在系统-系统基本参数-附件设置中添加pdf格式 并且将大小调大 第二步:在核心-内容模型-普通文章中添 ...
- 阿里云阿里免费ssl wap网站在手机微信、手机浏览器无法访问
图片可以访问,样式无法显示 https://css.cnbuses.com/css/wap/gonggong.css 1,怀疑是开了代理访问. 关闭后还是访问空白. 2.在手机浏览器打开,提示该网站的 ...
- 浏览器在线查看pdf文件 pdf.js的使用教程
谷歌浏览器可以直接在线查看pdf,而IE内核浏览器无法在线查看,默认是下载. 这里用到的是pdf.js,不仅支持IE内核浏览器,而且兼容手机查看pdf 官网地址:http://mozilla.gith ...
- alert 在手机浏览器会显示网址,怎么能去掉这个网址
之前就看到有人发过这帖子,现在自己也遇到这问题了. 目前想到的一个解决方案,是用jquery的模拟的alert插件进行代替,可是找的几个插件都不能实现alert的阻塞功能.怎么破 ,具体解决方案如下: ...
- 如何用浏览器在线查看.ipynb文件
当我们用jupyter notebook编辑好.ipynb文件后,肯定会想不用运行jupyter notebook也能方便得查看.ipynb的文件,如果直接打开.ipynb的文件,我们 ...
随机推荐
- CentOS环境下R语言的安装和配置
最近在看数据统计和分析,想到了R语言,于是就着手在自己的CentOS环境下进行安装和配置.步骤如下: 1.前往R官网下载安装包. 2.解压压缩包:tar xvzf R-3.2.2.tar.gz 3.进 ...
- Python学习之路——迭代器、生成器、算法基础、正则
一.迭代器: 迭代器是访问集合元素的一种方式. 迭代器对象是从集合的第一个元素开始访问,直到所有的元素被访问完结束. 迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退. 另外,迭代 ...
- CloudStack 物理网络架构
原文地址:http://www.shapeblue.com/cloudstack/understanding-cloudstacks-physical-networking-architecture/ ...
- poj 1442 Black Box(优先队列&Treap)
题目链接:http://poj.org/problem?id=1442 思路分析: <1>维护一个最小堆与最大堆,最大堆中存储最小的K个数,其余存储在最小堆中; <2>使用Tr ...
- 九度 和为S的连续正数序列
题目1354:和为S的连续正数序列 时间限制:2 秒 内存限制:32 兆 特殊判题:否 提交:2008 解决:622 题目描述: 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上 ...
- android -- 蓝牙 bluetooth (一) 入门
前段时间在 网上看了一些关于android蓝牙的文章,发现大部分是基于老版本(4.1以前含4.1)的源码,虽然无碍了解蓝牙的基本原理和工作流程,但对着4.2.2的代码看起来总是有些遗憾.所以针对4.2 ...
- [Swust OJ 1125]--又见GCD(数论,素数表存贮因子)
题目链接:http://acm.swust.edu.cn/problem/1125/ Time limit(ms): 1000 Memory limit(kb): 65535 Descriptio ...
- Android:OptionMenu
MainActivity: package com.example.optionmenu; import android.content.Intent; import android.os.Bundl ...
- Android短信拦截和电话拦截
MainActivity: package com.wyl.bctest; import android.support.v7.app.ActionBarActivity; import androi ...
- python成长之路——第六天
定义 Python 的 Class 比较特别,和我们习惯的静态语言类型定义有很大区别. 1. 使用一个名为 __init__ 的方法来完成初始化.2. 使用一个名为 __del__ 的方法来完成类似析 ...