微信或手機瀏覽器在線顯示office文件(已測試ios、android)
最近開發(fā)微信企業(yè)號,發(fā)現(xiàn)微信andriod版內(nèi)置瀏覽器在打開文件方面有問題,但是ios版沒有問題,原因是ios版使用的是safari瀏覽器 支持文檔直接打開,但是andriod版使用的是騰訊瀏覽器x5內(nèi)核,不知道什么原因不支持,可能是集成出現(xiàn)的問題,這里提供解決方法,這種方法也同樣適用手機瀏覽器或者安卓開發(fā)。通過此方法可以在微信上開發(fā)自己的第三方應(yīng)用,或者解決自己的項目問題,解決方法及核心代碼如下:
1、判斷瀏覽器類型
HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//里面包含了設(shè)備類型
2、IOS版直接使用流輸出
Andriod版利用openoffice+jod轉(zhuǎn)換成html,然后對html內(nèi)容重新編輯,文件中有圖片的將路徑改為網(wǎng)絡(luò)路徑或者采用流輸出(改成網(wǎng)絡(luò)路徑注意特殊符號,如+號會變成空格)
/**
* 從OA上抓取文件
* author 牟云飛
* company 海頤軟件股份有限公司
* tel 15562579597
* qq 1147417467
* team 客服產(chǎn)品中心/于洋
* @return
*/
public String getFileFromOa(){
HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//里面包含了設(shè)備類型
if(-1!=userAgent.indexOf("iPhone")){
//-----------------//
//此方法需要瀏覽器自己能夠打開,ios可以但是微信andriod版內(nèi)置瀏覽器不支持
//-----------------//
//如果是蘋果手機
//獲得文件地址
String fileUrl = ServletActionContext.getRequest().getParameter("fileUrl");
fileUrl.replaceAll("%20", "\\+");//轉(zhuǎn)換加號
String strURL = MessageUtil.oaUrl+fileUrl;
String fileType=strURL.substring(strURL.lastIndexOf(".")+1,strURL.length());
//獲得圖片的數(shù)據(jù)流
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", "\\+");//轉(zhuǎn)換加號
String strURL = MessageUtil.oaUrl+fileUrl;
//在本地存放OA文件,然后轉(zhuǎn)換成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()){
//判斷文件夾是否存在,創(chuàng)建文件夾
String oaFilePath=path + "OaFile";//存放OA文檔的文件夾路徑;
File oaFiles=new File(oaFilePath);
if(!oaFiles.exists()){
//如果文件夾不存在創(chuàng)建文件夾
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();
//轉(zhuǎn)換成html
String htmlFilePath =path + "OaFileToHtml";//OA文件轉(zhuǎn)成html的位置
String htmlcontext=ConvertFileToHtml.toHtmlString(oafile, htmlFilePath);
req.setAttribute("htmlcontext", htmlcontext);
}else{
//已經(jīng)存在轉(zhuǎn)換成功的文檔
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);
// 返回經(jīng)過清潔的html文本
req.setAttribute("htmlcontext", ConvertFileToHtml.clearFormat(htmlStr, ""));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "lookfile";
}
}
-------------------將word轉(zhuǎn)換成html文件,并讀取內(nèi)容-------------------------
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 客服產(chǎn)品中心/于洋
*
*/
public class ConvertFileToHtml {
/**
* 將word文檔轉(zhuǎn)換成html文檔
* @param docFile 需要轉(zhuǎn)換的word文檔
* @param filepath 轉(zhuǎn)換之后html的存放路徑
* @return 轉(zhuǎn)換之后的html文件
*/
public static File convert(File docFile, String filepath) {
// 創(chuàng)建保存html的文件
String fileName=docFile.getName();
File htmlFile = new File(filepath + "/" + fileName + ".html");
// 創(chuàng)建Openoffice連接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 連接
con.connect();
} catch (ConnectException e) {
System.out.println("獲取OpenOffice連接失敗...");
e.printStackTrace();
}
// 創(chuàng)建轉(zhuǎn)換器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 轉(zhuǎn)換文檔問html
converter.convert(docFile, htmlFile);
// 關(guān)閉openoffice連接
con.disconnect();
return htmlFile;
}
/**
*
* 將word轉(zhuǎn)換成html文件,并且獲取html文件代碼。
* @param docFile 需要轉(zhuǎn)換的文檔
* @param filepath 文檔中圖片的保存位置
* @return 轉(zhuǎn)換成功的html代碼
*/
public static String toHtmlString(File docFile, String filepath) {
// 轉(zhuǎn)換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);
// 返回經(jīng)過清潔的html文本
return clearFormat(htmlStr, filepath);
}
/**
*
* 清除一些不需要的html標(biāo)記
*/
public static String clearFormat(String htmlStr, String docImgPath) {
// 獲取body內(nèi)容的正則
String bodyReg = "<BODY .*</BODY>";
Pattern bodyPattern = Pattern.compile(bodyReg);
Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
if (bodyMatcher.find()) {
// 獲取BODY內(nèi)容,并轉(zhuǎn)化BODY標(biāo)簽為DIV
htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV").replaceAll("</BODY>", "</DIV>");
}
// 調(diào)整圖片地址,這里將圖片路徑改為網(wǎng)絡(luò)路徑
htmlStr = htmlStr.replaceAll("<IMG SRC=\"../","<IMG SRC=\"" + MessageUtil.webUrl+"/******.do?action=***);
//特殊處理一下+號,因為網(wǎng)絡(luò)傳輸+會變成空格,用%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>轉(zhuǎn)換成</div></div>保留樣式
// content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
// "<div$2</div>");
// 把<P></P>轉(zhuǎn)換成</div></div>并刪除樣式
htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
// 刪除不需要的標(biāo)簽
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;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android中將一個圖片切割成多個圖片的實現(xiàn)方法
有種場景,我們想將一個圖片切割成多個圖片。比如我們在開發(fā)一個拼圖的游戲,就首先要對圖片進行切割2013-05-05
android獲取監(jiān)聽SD Card狀態(tài)的方法
這篇文章主要介紹了android獲取監(jiān)聽SD Card狀態(tài)的方法,涉及Android實現(xiàn)SD Card監(jiān)聽的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
android實現(xiàn)視頻的加密和解密(使用AES)
本篇文章主要介紹了android實現(xiàn)視頻的加密和解密(使用AES),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Android使用RecyclerView實現(xiàn)投票系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Android使用RecyclerView實現(xiàn)投票系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
Android Studio通過Artifactory搭建本地倉庫優(yōu)化編譯速度的方法
這篇文章主要介紹了Android Studio通過Artifactory搭建本地倉庫優(yōu)化編譯速度的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Android學(xué)習(xí)筆記之應(yīng)用單元測試實例分析
這篇文章主要介紹了Android學(xué)習(xí)筆記之應(yīng)用單元測試,結(jié)合實例形式較為詳細(xì)的分析了Android單元測試的實現(xiàn)原理與具體步驟,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
Android編程簡單設(shè)置ListView分割線的方法
這篇文章主要介紹了Android編程簡單設(shè)置ListView分割線的方法,涉及Android布局簡單操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2017-02-02

