Using webView's loadDataWithBaseURL not loading images from sdcard

淺唱寂寞╮ 提交于 2019-12-20 04:16:10

问题


I would like to set some html content in my webview with some pictures. I've read on the internet i must use loadDataWithBaseUrl to do such a thing because i need to link the folder of images (basUrl) in order.

My html content nicely loads, i can even ran the javascripts perfectly, but for some reason my images cannot be loaded.

Somewhere i've read there are some security reasons and thats why i cant load images from sd card to webview and some says it can be easily done via loadDataWithBaseUrl, so i really dont know which one is true.

Here is my method i tried, maybe with some mistakes so dont be rude:

I got my html file here:

mnt/sdcard/com.mypackage.myproject/3/3.html

My images are here:

mnt/sdcard/com.mypackage.myproject/3/images/Cover.png

And this is my content loading:

myWebView.loadDataWithBaseURL("file:///mnt/sdcard/com.mypackage.myproject/3", myHtml, "text/html", "utf-8", "");

In my html code:

<img src="images/Cover.png" alt="Cover.png" height="820"/>

So as you see i give the baseUrl, and for some reason the webview cannot load my images.

As many said, this can be a solution:

mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file:/"+ base + "/test.jpg";
String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>";
mWebView.loadData(html, "text/html","utf-8");

BUT, i have 700 different html files and there are many images in many different places... so i cannot modify the html code.

Is there a way to link the image folder to my html files to properly use them as a baseUrl?


回答1:


You have a syntax error in your loading statement. You have to put : after file

myWebView.loadDataWithBaseURL("file:///mnt/sdcard/com.mypackage.myproject/3", myHtml, "text/html", "utf-8", "");



回答2:


You don't need to put full path of your image into html.

img src="images/test1.jpg"

Instead

img src=\""+ imagePath + "\"



来源:https://stackoverflow.com/questions/11754288/using-webviews-loaddatawithbaseurl-not-loading-images-from-sdcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!