Hareesh
Hareesh

Reputation: 943

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

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.

I want to load that base64 data string in webview using:

webview.loadData(urlString, "text/html; charset=utf-8", null);

Sample:

       String urlString = getIntent().getStringExtra("base64String");
       String mimeType = getIntent().getStringExtra("MimeType");

WebSettings settings = webView.getSettings();
    settings.setDefaultTextEncodingName("utf-8");
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        String base64 = Base64.encodeToString(urlString.getBytes(), Base64.DEFAULT);
        webView.loadData(urlString, "text/html; charset=utf-8", "base64");
    } else {
        String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
        webView.loadData(header + urlString, "text/html; chartset=UTF-8", null);

    }

Upvotes: 7

Views: 11733

Answers (2)

Sandip_Jahdav
Sandip_Jahdav

Reputation: 147

Just Try it:

webView.loadData(urlString, "text/html; charset=utf-8", "base64");

Upvotes: 4

Jitesh Upadhyay
Jitesh Upadhyay

Reputation: 5260

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);

Upvotes: 0

Related Questions