Micro-mail or mobile browser online display Office files (tested iOS, Android) _android

Source: Internet
Author: User
Tags readline stringbuffer

The recent development of the micro-credit enterprise number, found that the micro-andriod version of the built-in browser to open the file problem, but the iOS version is not a problem, because the iOS version using the Safari browser support document directly open, but the andriod version using the Tencent browser X5 kernel, Don't know why not support, may be the integration of problems, here provide solutions, this method is also suitable for mobile phone browser or Android development. This approach allows you to develop your own third-party applications on a micro-letter or solve your own project problems, and the solution and core code are as follows:
1, determining the browser type
httpservletrequest req = Servletactioncontext.getrequest ();
String useragent=req.getheader ("user-agent");//containing device type
2, iOS version direct use flow output
Andriod version of the use of Openoffice+jod converted to HTML, and then the HTML content to be edited, the file has a picture of the path to the network path or flow output (change to network path note special symbols, such as + number will become a space)

/** * FROM OA crawl file * Author Shuiyunfei * company Hai Yi Software Co., Ltd. * Tel 15562579597 * QQ 1147417467 * Team Customer Service Product Center/yu * @return *
 /public String Getfilefromoa () {HttpServletRequest req = Servletactioncontext.getrequest (); String Useragent=req.getheader ("user-agent");//inside contains the device type if ( -1!=useragent.indexof ("IPhone")) {//----------------- This method requires the browser to be able to open itself, iOS can but the micro-andriod version of the built-in browser does not support//-----------------///If it is an Apple phone//Get file address String FileUrl = servletaction
 Context.getrequest (). GetParameter ("FileUrl");
 Fileurl.replaceall ("%20", "\\+");//convert plus String strurl = Messageutil.oaurl+fileurl; String filetype=strurl.substring (Strurl.lastindexof (".")
 +1,strurl.length ());
 Get the data stream of the picture try {url oaurl = new URL (strurl);
 HttpURLConnection httpconn = (httpurlconnection) oaurl.openconnection ();
 InputStream in = Httpconn.getinputstream ();
 Gets the output stream 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 (); 
 Output picture information 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{//If non-Apple phones, process documents themselves//Get file address String FileUrl = Servletactioncontext.getrequest (). GetParameter ("FileUrl"); Fileurl.replaceall ("%2b", "\\+");/convert plus String strurl = Messageutil.oaurl+fileurl;
 Store the OA file locally, then convert to HTML, and then modify the picture path in the document, and finally output to the page try {URL oaurl = new URL (strurl);
 HttpURLConnection httpconn = (httpurlconnection) oaurl.openconnection ();
 InputStream in = Httpconn.getinputstream ();
 Gets the output stream httpservletresponse response = Servletactioncontext.getresponse ();
 Req.setcharacterencoding ("UTF-8");
 Response.setcharacterencoding ("UTF-8");
 
 String name=fileurl.substring (Fileurl.lastindexof ("/") +1, Fileurl.length ());
 First, determine whether a String Path=req.getrealpath ("") exists locally;
 Path=path.substring (0, Path.lastindexof ("\") +1);
 File Htmlfile=new file (path + "oafiletohtml\\" +name+ ". html");
  if (!htmlfile.exists ()) {//To determine whether the folder exists, create a folder String Oafilepath=path + "oafile";//the folder path where the OA document is stored;
  File Oafiles=new file (Oafilepath);
  if (!oafiles.exists ()) {//If the folder does not exist Create folder Oafiles.mkdirs ();
  //The OA message is stored in the local file Oafile=new file (oafiles+ file.separator +name);
  OutputStream out = new FileOutputStream (oafile); Output picture information 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 (); Convert to HTML string htmlfilepath =path + "oafiletohtml";//oa file to HTML location String Htmlcontext=convertfiletohtml.tohtmlstrin
  G (Oafile, Htmlfilepath);
 Req.setattribute ("Htmlcontext", Htmlcontext);
  }else{//There is already a successfully converted document StringBuffer HTMLSB = new StringBuffer (); try {bufferedreader br = new BufferedReader (new InputStreamReader (Htmlfile), Charset.forname ("
  gb2312 "));
  while (Br.ready ()) {Htmlsb.append (Br.readline ());
  } br.close ();
  catch (FileNotFoundException e) {e.printstacktrace ();
  catch (IOException e) {e.printstacktrace ();
  }//html file string htmlstr = Htmlsb.tostring ();
  System.out.println ("htmlstr=" + htmlstr);
 Returns a clean HTML text req.setattribute ("Htmlcontext", Convertfiletohtml.clearformat (Htmlstr, "")); } catch (Malformedurlexception e) {E.printstacktracE ();
 catch (IOException e) {e.printstacktrace ();
 Return to "Lookfile"; 
 }
 
 }

The

-------------------converts word to an HTML file and reads the contents-------------------------

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;
 /** * * Port Start command: * soffice-headless-accept= "SOCKET,PORT=8100;URP; * * Author Shuiyunfei * company Hai Yi Software Co., Ltd. * Tel 15562579597 * QQ 1147417467 * Team Customer Service Product Center/Yu */public class Con vertfiletohtml {/** * Convert Word document to HTML document * @param docfile the Word document that needs to be converted * @param filepath after conversion the HTML storage path * @return converted H TML file */public staticFile convert (file Docfile, string filepath) {//Create a document to save HTML string filename=docfile.getname ();
 File Htmlfile = new file (filepath + "/" + FileName + ". html");
 Create OpenOffice connection Openofficeconnection con = new socketopenofficeconnection (8100);
 try {//Connect con.connect ();
 catch (Connectexception e) {System.out.println ("Get OpenOffice Connection Failed ...");
 E.printstacktrace ();
 //Create converter Documentconverter converter = new openofficedocumentconverter (con);
 Convert document Ask HTML Converter.convert (docfile, htmlfile);
 Close OpenOffice Connection con.disconnect ();
 return htmlfile;
 /** * Converts word to an HTML file and gets the HTML file code. * @param docfile documents that need to be converted * @param the filepath of a picture in a document * @return conversion successful HTML code/public static String tohtmlstring (File
 Docfile, String filepath) {//Convert Word document file Htmlfile = CONVERT (docfile, filepath);
 System.out.println (Htmlfile.getabsolutepath ());
 Gets the HTML file stream 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 ();
 Delete temporary files//htmlfile.delete ();
 catch (FileNotFoundException e) {e.printstacktrace ();
 catch (IOException e) {e.printstacktrace ();
 }//html file string htmlstr = Htmlsb.tostring ();
 System.out.println ("htmlstr=" + htmlstr);
 Returns the clean HTML text return Clearformat (HTMLSTR, filepath); 
 /** * * * Clear some unwanted HTML tags/public static string Clearformat (String htmlstr, String docimgpath) {//Get regular for body content
 String Bodyreg = "<body .*</body>";
 Pattern Bodypattern = Pattern.compile (Bodyreg);
 Matcher Bodymatcher = Bodypattern.matcher (HTMLSTR); if (Bodymatcher.find ()) {//Get body content and convert body tag to DIV htmlstr = Bodymatcher.group (). Replacefirst ("<body", "<div").
 ReplaceAll ("</BODY>", "</DIV>"); ///Adjust picture address, this will change picture path to network path HTMLSTR = Htmlstr.replaceall ("</P> to </div></div> retention style/content = Content.replaceall ("(<p)" ([^>]*>.*?)
 (<\\/P>) ",//" <div$2</div> "); Convert <P></P> to </div></div> delete style Htmlstr = Htmlstr.replaceall (<p) ([^>]*) (>.*?)
 (<\\/P>) "," <p$3</p> "); Delete unwanted tags htmlstr = htmlstr.replaceall ("<[/]?" ( Font| font|span| span|xml| xml|del| del|ins| ins|meta| meta|
 [ovwxpovwxp]:\\w+) [^>]*?> "," "); Delete unwanted Properties htmlstr = Htmlstr.replaceall ("<" ([^>]*) (?: Lang| lang|class| class|style| style|size| size|face| face| [ovwxpovwxp]:\\w+] = (?: ' [^ ']* ' |\ '] [^\ "\"]*\ "\" |[ ^>]+) ([^>]*) > "," <$1$2>");

 return htmlstr;

 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.