showing image from sdcard with webview not working

2020-07-17 08:04发布

问题:

I have downloaded map750.png file in the root of sdcard, but when I try to show it within a webview with some text, only the text is shown. Could you help me to find what is wrong in the code? thanks.

setContentView(R.layout.webview);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
    mWebView.loadData(html, "text/html","utf-8");

I edit the post to add the solution suggested by oneilse14, thanks!!

setContentView(R.layout.webview);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
    mWebView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");

回答1:

Check out loadDataWithBaseURL() in the Developer docs

http://developer.android.com/reference/android/webkit/WebView.html

loadData() has certain restrictions on what it can display. This method is able to display local device files like you are trying to do.



回答2:

Try this,

        final String fileName = "file:///mnt/sdcard/1.jpg";
        final String mimeType = "text/html";
        final String encoding = "utf-8";
        final String html = "<img src=\""+fileName+"\">";
        webView.loadDataWithBaseURL("", html, mimeType, encoding, "");


回答3:

Note that the access using the file:// schema can fail due security restrictions.

Another approach is to use the URI of a ContentProvider that handles the local file access. Overwrite openFile(Uri, String) in a subclass of ContentProvider for this approach.