andriod版瀏覽器不支援文件直接開啟的解決辦法
最近开发微信企业号,发现微信andriod版内置浏览器在打开文件方面有问题,但是ios版没有问题,原因是ios版使用的是safari浏览器 支持文档直接打开,但是andriod版使用的是腾讯浏览器x5内核,不知道什么原因不支持,可能是集成出现的问题,这里提供解决方法,这种方法也同样适用手机浏览器或者安卓开发。通过此方法可以在微信上开发自己的第三方应用,或者解决自己的项目问题,解决方法及核心代码如下:
1、判断浏览器类型
HttpServletRequest req = ServletAction Context.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文件,并读取内容-------------------------
此类借鉴原地址并修改jadethao.iteye.com/blog/1817738
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标签为p htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<p").replaceAll("</BODY>", "</p>"); } // 调整图片地址,这里将图片路径改为网络路径 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>转换成</p></p>保留样式 // content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)", // "<p$2</p>"); // 把<P></P>转换成</p></p>并删除样式 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; } }
【相关推荐】
1. 特别推荐:“php程序员工具箱”V0.1版本下载
2. 微信小程序完整源码下载
3. 微信小程序demo:阳淘
以上是andriod版瀏覽器不支援文件直接開啟的解決辦法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

WebSocket服務器返回401後瀏覽器無反應的處理方法在使用Netty開發WebSocket服務器時,經常會遇到驗證token的需求。 �...

關於JavaScript無法獲取用戶電腦硬件信息的原因探討在日常編程中,許多開發者會好奇為什麼JavaScript無法直接獲�...

關於JWT和Session的困惑與解答許多初學者在學習JWT和Session時,常常會對其本質和適用場景感到困惑。本文將圍繞J...

USDT轉賬地址錯誤後,首先確認轉賬已發生,然後根據錯誤類型採取措施。 1.確認轉賬:查看交易記錄,獲取並在區塊鏈瀏覽器上查詢交易哈希值。 2.採取措施:若地址不存在,等待資金退回或聯繫客服;若為無效地址,聯繫客服並尋求專業幫助;若轉給了他人,嘗試聯繫收款方或尋求法律幫助。

在Java中生成帶參數的微信小程序二維碼並將其顯示在HTML頁面上,是一個常見的需求。本文將詳細探討如何使用J...

可以。兩個交易所之間可以互相轉幣,只要支持相同的幣種和網絡。步驟包括:1. 獲取收款地址,2. 發起提幣請求,3. 等待確認。注意事項:1. 選擇正確的轉賬網絡,2. 仔細核對地址,3. 了解手續費,4. 注意到賬時間,5. 確認交易所支持該幣種,6. 注意最小提幣數量。

註冊歐易賬戶的步驟如下:1.準備有效郵箱或手機號和穩定網絡。 2.訪問歐易官網。 3.進入註冊頁面。 4.選擇郵箱或手機號註冊,填寫信息。 5.獲取並填寫驗證碼。 6.同意用戶協議。 7.完成註冊並登錄,進行KYC和設置安全措施。

幣安是全球數字資產交易生態的霸主,其特點包括:1. 日均交易量突破$1500億,支持500 交易對,覆蓋98%主流幣種;2. 創新矩陣涵蓋衍生品市場、Web3佈局和教育體系;3. 技術優勢為毫秒級撮合引擎,峰值處理量達140萬筆/秒;4. 合規進展持有15國牌照,並在歐美設立合規實體。
