我的应用程序需要从服务器下载zip,解压缩并使用webview中的文件。
我已完成上述所有步骤,但webview仅显示html。 css和javascript无法正常工作。
所有路径都是相对路径,文件在浏览器上工作。
webview的代码就是这个
WebSettings ws = myWebView.getSettings();
ws.setAllowFileAccess(true);
String dir = getFilesDir().getAbsolutePath();
String saveDir = dir+"/Download/";
Toast.makeText(getApplicationContext(),"file:/"+ saveDir+"352_1332.html" ,Toast.LENGTH_LONG).show();
myWebView.loadUrl("file://"+saveDir+"352_1332.html");
答案 0 :(得分:0)
您必须在手机中的特定位置解压缩该文件并提供该文件夹路径
webView.loadDataWithBaseURL("file://"+outPutFolder, finalDataToLoad, "text/html", "utf-8", null);
这里outputFolder是文件夹路径,finalDataToLoad是你要加载的数据/ html
private void DownloadResource(String directory) {
try {
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
Log.d("Href", rs.getHref());
File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, rs.getHref());
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
}
}
这里的书是我的epubfile
答案 1 :(得分:0)
我猜资源的WebView查找(css,js)出错了。 例如,您的352_1332.html如下所示:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<!-- some elements -->
</body>
</html>
默认情况下,webview不会尝试在 saveDir 目录下找到stylesheet.css。你必须指向该文件。为此,您必须覆盖WebViewClient.shouldInterceptRequest:
myWebView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
//url = stylesheet.css -> now point to resource file
FileInputStream data = null;
try {
data = new FileInputStream("file://" + saveDir + File.separator + url));
} catch (FileNotFoundException e) {
return null;
}
return new WebResourceResponse(this.getMimeTyp(url), null, data);
}
}
/**
* returns mime-typ
* @param url String
* @return String
*/
private String getMimeTyp (String url) {
if (url.endsWith(".css") == true) {
return "text/css";
} else if (url.endsWith(".js") == true) {
return "text/javascript";
} else if (url.endsWith(".html") == true) {
return "text/html";
} else if (url.endsWith(".png") == true) {
return "image/png";
} else if (url.endsWith(".jpg") == true || url.contains(".jpeg") == true) {
return "image/jpeg";
} else if (url.endsWith(".gif") == true) {
return "image/gif";
} else {
//fallback for everything else
return "application/octet-stream";
}
}
以上代码完全未经测试......