微信或手机浏览器在线显示office文件(已测试ios、android)
最近开发微信企业号,发现微信andriod版内置浏览器在打开文件方面有问题,但是ios版没有问题,原因是ios版使用的是safari浏览器支持文档直接打开,但是andriod版使用的是腾讯浏览器x5内核,不知道什么原因不支持,可能是集成出现的问题,这里提供解决方法,这种方法也同样适用手机浏览器或者安卓开发。通过此方法可以在微信上开发自己的第三方应用,或者解决自己的项目问题,解决方法及核心代码如下:
1、判断浏览器类型
HttpServletRequestreq=ServletActionContext.getRequest();
StringuserAgent=req.getHeader("User-Agent");//里面包含了设备类型
2、IOS版直接使用流输出
Andriod版利用openoffice+jod转换成html,然后对html内容重新编辑,文件中有图片的将路径改为网络路径或者采用流输出(改成网络路径注意特殊符号,如+号会变成空格)
/**
*从OA上抓取文件
*author牟云飞
*company海颐软件股份有限公司
*tel15562579597
*qq1147417467
*team客服产品中心/于洋
*@return
*/
publicStringgetFileFromOa(){
HttpServletRequestreq=ServletActionContext.getRequest();
StringuserAgent=req.getHeader("User-Agent");//里面包含了设备类型
if(-1!=userAgent.indexOf("iPhone")){
//-----------------//
//此方法需要浏览器自己能够打开,ios可以但是微信andriod版内置浏览器不支持
//-----------------//
//如果是苹果手机
//获得文件地址
StringfileUrl=ServletActionContext.getRequest().getParameter("fileUrl");
fileUrl.replaceAll("%20","\\+");//转换加号
StringstrURL=MessageUtil.oaUrl+fileUrl;
StringfileType=strURL.substring(strURL.lastIndexOf(".")+1,strURL.length());
//获得图片的数据流
try{
URLoaUrl=newURL(strURL);
HttpURLConnectionhttpConn=(HttpURLConnection)oaUrl.openConnection();
InputStreamin=httpConn.getInputStream();
//获取输出流
HttpServletResponseresponse=ServletActionContext.getResponse();
req.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Stringname=fileUrl.substring(fileUrl.lastIndexOf("/")+1,fileUrl.length());
response.setHeader("Content-Disposition",
"attachment;filename="+
newString((name).getBytes(),
"iso-8859-1"));
if("doc".equals(fileType)||"docx".equals(fileType)){
response.setContentType("application/msword");
}elseif("xls".equals(fileType)||"xlsx".equals(fileType)){
response.setContentType("application/msexcel");
}else{
response.setContentType("application/"+fileType);
}
OutputStreamout=response.getOutputStream();
//输出图片信息
byte[]bytes=newbyte[1024];
intcnt=0;
while((cnt=in.read(bytes,0,bytes.length))!=-1){
out.write(bytes,0,cnt);
}
out.flush();
out.close();
in.close();
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}else{
//如果非苹果手机,自己处理文档
//获得文件地址
StringfileUrl=ServletActionContext.getRequest().getParameter("fileUrl");
fileUrl.replaceAll("%2B","\\+");//转换加号
StringstrURL=MessageUtil.oaUrl+fileUrl;
//在本地存放OA文件,然后转换成html,再对文档中的图片路径进行修改,最后输出到页面
try{
URLoaUrl=newURL(strURL);
HttpURLConnectionhttpConn=(HttpURLConnection)oaUrl.openConnection();
InputStreamin=httpConn.getInputStream();
//获取输出流
HttpServletResponseresponse=ServletActionContext.getResponse();
req.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Stringname=fileUrl.substring(fileUrl.lastIndexOf("/")+1,fileUrl.length());
//首先判断本地是否存在
Stringpath=req.getRealPath("");
path=path.substring(0,path.lastIndexOf("\\")+1);
FilehtmlFile=newFile(path+"OaFileToHtml\\"+name+".html");
if(!htmlFile.exists()){
//判断文件夹是否存在,创建文件夹
StringoaFilePath=path+"OaFile";//存放OA文档的文件夹路径;
FileoaFiles=newFile(oaFilePath);
if(!oaFiles.exists()){
//如果文件夹不存在创建文件夹
oaFiles.mkdirs();
}
//将OA消息存入本地
Fileoafile=newFile(oaFiles+File.separator+name);
OutputStreamout=newFileOutputStream(oafile);
//输出图片信息
byte[]bytes=newbyte[1024];
intcnt=0;
while((cnt=in.read(bytes,0,bytes.length))!=-1){
out.write(bytes,0,cnt);
}
out.flush();
out.close();
in.close();
//转换成html
StringhtmlFilePath=path+"OaFileToHtml";//OA文件转成html的位置
Stringhtmlcontext=ConvertFileToHtml.toHtmlString(oafile,htmlFilePath);
req.setAttribute("htmlcontext",htmlcontext);
}else{
//已经存在转换成功的文档
StringBufferhtmlSb=newStringBuffer();
try{
BufferedReaderbr=newBufferedReader(newInputStreamReader(newFileInputStream(htmlFile),Charset.forName("gb2312")));
while(br.ready()){
htmlSb.append(br.readLine());
}
br.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//HTML文件字符串
StringhtmlStr=htmlSb.toString();
//System.out.println("htmlStr="+htmlStr);
//返回经过清洁的html文本
req.setAttribute("htmlcontext",ConvertFileToHtml.clearFormat(htmlStr,""));
}
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
return"lookfile";
}
}
-------------------将word转换成html文件,并读取内容-------------------------
packagecom.haiyisoft.wx.util;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.net.ConnectException;
importjava.nio.charset.Charset;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
importcom.artofsolving.jodconverter.DocumentConverter;
importcom.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
importcom.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
importcom.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
/**
**端口启动命令:
*soffice-headless-accept="socket,port=8100;urp;
*
*
*author牟云飞
*company海颐软件股份有限公司
*tel15562579597
*qq1147417467
*team客服产品中心/于洋
*
*/
publicclassConvertFileToHtml{
/**
*将word文档转换成html文档
*@paramdocFile需要转换的word文档
*@paramfilepath转换之后html的存放路径
*@return转换之后的html文件
*/
publicstaticFileconvert(FiledocFile,Stringfilepath){
//创建保存html的文件
StringfileName=docFile.getName();
FilehtmlFile=newFile(filepath+"/"+fileName+".html");
//创建Openoffice连接
OpenOfficeConnectioncon=newSocketOpenOfficeConnection(8100);
try{
//连接
con.connect();
}catch(ConnectExceptione){
System.out.println("获取OpenOffice连接失败...");
e.printStackTrace();
}
//创建转换器
DocumentConverterconverter=newOpenOfficeDocumentConverter(con);
//转换文档问html
converter.convert(docFile,htmlFile);
//关闭openoffice连接
con.disconnect();
returnhtmlFile;
}
/**
*
*将word转换成html文件,并且获取html文件代码。
*@paramdocFile需要转换的文档
*@paramfilepath文档中图片的保存位置
*@return转换成功的html代码
*/
publicstaticStringtoHtmlString(FiledocFile,Stringfilepath){
//转换word文档
FilehtmlFile=convert(docFile,filepath);
System.out.println(htmlFile.getAbsolutePath());
//获取html文件流
StringBufferhtmlSb=newStringBuffer();
try{
BufferedReaderbr=newBufferedReader(newInputStreamReader(newFileInputStream(htmlFile),Charset.forName("gb2312")));
while(br.ready()){
htmlSb.append(br.readLine());
}
br.close();
//删除临时文件
//htmlFile.delete();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//HTML文件字符串
StringhtmlStr=htmlSb.toString();
//System.out.println("htmlStr="+htmlStr);
//返回经过清洁的html文本
returnclearFormat(htmlStr,filepath);
}
/**
*
*清除一些不需要的html标记
*/
publicstaticStringclearFormat(StringhtmlStr,StringdocImgPath){
//获取body内容的正则
StringbodyReg="<BODY.*</BODY>";
PatternbodyPattern=Pattern.compile(bodyReg);
MatcherbodyMatcher=bodyPattern.matcher(htmlStr);
if(bodyMatcher.find()){
//获取BODY内容,并转化BODY标签为DIV
htmlStr=bodyMatcher.group().replaceFirst("<BODY","<DIV").replaceAll("</BODY>","</DIV>");
}
//调整图片地址,这里将图片路径改为网络路径
htmlStr=htmlStr.replaceAll("<IMGSRC=\"../","<IMGSRC=\""+MessageUtil.webUrl+"/******.do?action=***);
//特殊处理一下+号,因为网络传输+会变成空格,用%2B替换+号
Stringtemp1=htmlStr.substring(htmlStr.indexOf("action=***"),htmlStr.length());
Stringtemp2=temp1.substring(0,temp1.indexOf("."));
Stringtemp3=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>");
returnhtmlStr;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。