


WeChat or mobile browser displays office files online (tested on ios and android)
Jan 17, 2017 pm 02:21 PM最近開發(fā)微信企業(yè)號,發(fā)現(xiàn)微信andriod版內(nèi)置瀏覽器在打開文件方面有問題,但是ios版沒有問題,原因是ios版使用的是safari瀏覽器 支持文檔直接打開,但是andriod版使用的是騰訊瀏覽器x5內(nèi)核,不知道什么原因不支持,可能是集成出現(xiàn)的問題,這里提供解決方法,這種方法也同樣適用手機(jī)瀏覽器或者安卓開發(fā)。通過此方法可以在微信上開發(fā)自己的第三方應(yīng)用,或者解決自己的項(xià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)置瀏覽器不支持 //-----------------// //如果是蘋果手機(jī) //獲得文件地址 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{ //如果非蘋果手機(jī),自己處理文檔 //獲得文件地址 String fileUrl = ServletActionContext.getRequest().getParameter("fileUrl"); fileUrl.replaceAll("%2B", "\\+");//轉(zhuǎn)換加號 String strURL = MessageUtil.oaUrl+fileUrl; //在本地存放OA文件,然后轉(zhuǎn)換成html,再對文檔中的圖片路徑進(jìn)行修改,最后輸出到頁面 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(); // 刪除臨時(shí)文件 //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=***); //特殊處理一下+號,因?yàn)榫W(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í)有所幫助,也希望大家多多支持PHP中文網(wǎng)。
更多微信或手機(jī)瀏覽器在線顯示office文件(已測試ios、android)相關(guān)文章請關(guān)注PHP中文網(wǎng)!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)