編輯:關於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文件,並讀取內容-------------------------
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;
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。
Android開發之自定義控件(二)---onLayout詳解
話說一個乞丐在看一個程序員寫程序,程序員遇到一個問題怎麼都解決不了,這時乞丐說這少個分號,程序員照做結果問題解決了,就問:你怎麼知道?乞丐笑笑說:
Android N 通知欄和快捷通知欄帶來的改變
Android N 通知欄和快捷通知欄帶來的改變Android N 引入了一些新的API,允許應用發布具有高度可見性和交互性的通知。Android N 擴展了現有 Rem
Android Activity生命周期都該做哪些事情?
Android系統根據生命周期的不同階段喚起對應的回調函數來執行代碼。系統存在啟動與銷毀一個activity的一套有序的回調函數。本節來討論下不同生命周期的回調函數裡都該
Android App中各種數據保存方式的使用實例總結
少量數據保存之SharedPreferences接口實例SharedPreferences數據保存主要是通過鍵值的方式存儲在xml文件中xml文件在data/此程序的包名