微信或手機瀏覽器線上顯示office檔案(已測試ios、android)_Android

來源:互聯網
上載者:User

最近開發微信企業號,發現微信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; }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.