How to load any format of base64 data to webview in Android?

后端 未结 2 1458
一个人的身影
一个人的身影 2021-02-06 11:52

I am implementing an android application related to Webview. I am getting base64 data string from server that data format may be jpg or pdf file or doc file etc

相关标签:
2条回答
  • 2021-02-06 12:12

    please have alook at https://github.com/gregko/WebArchiveReader for a good example and hope it may help you.

    byte[] imageRaw = null;
      try {
         URL url = new URL("http://some.domain.tld/somePicture.jpg");
         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
         InputStream in = new BufferedInputStream(urlConnection.getInputStream());
         ByteArrayOutputStream out = new ByteArrayOutputStream();
    
         int c;
         while ((c = in.read()) != -1) {
             out.write(c);
         }
         out.flush();
    
         imageRaw = out.toByteArray();
    
         urlConnection.disconnect();
         in.close();
         out.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
    
      String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
    
      String urlStr   = "http://example.com/my.jpg";
      String mimeType = "text/html";
      String encoding = null;
      String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
    
      WebView wv;
      wv = (WebView) findViewById(R.id.webview);
      wv.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
    
    0 讨论(0)
  • 2021-02-06 12:16

    Just Try it:

    webView.loadData(urlString, "text/html; charset=utf-8", "base64");
    
    0 讨论(0)
提交回复
热议问题