近期開發微信企業號,發現微信andriod版內置瀏覽器在打開文件方面有問題,但是ios版沒有問題。緣由是ios版使用的是safari瀏覽器 支持文檔直接打開。但是andriod版使用的是騰訊瀏覽器x5內核。不知道什麼緣由不支持。多是集成出現的問題,這裏提供解決方法。這樣的方法也相同適用手機瀏覽器或者安卓開發。html
經過此方法可以在微信上開發本身的第三方應用。或者解決本身的項目問題,解決方法及核心代碼例如如下:java
一、推斷瀏覽器類型ios
HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//裏面包括了設備類型web
二、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/1817738app
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+)[^>]*?less
>",""); // 刪除不需要的屬性 htmlStr = htmlStr.replaceAll("<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>","<$1$2>"); return htmlStr; } } socket