如何在Android中将任何格式的base64数据加载到webview?

Har*_*esh 5 base64 android webview

我正在实现一个与Webview相关的android应用程序.我从服务器获取base64数据字符串,数据格式可能是jpg或pdf文件或doc文件等.

我想使用以下方法在webview中加载该base64数据字符串:

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

样品:

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

    }
Run Code Online (Sandbox Code Playgroud)

Jit*_*yay 0

请查看https://github.com/gregko/WebArchiveReader以获得一个很好的示例,希望它可以帮助您。

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);
Run Code Online (Sandbox Code Playgroud)