Android webview文件导出怎么做?
时间: 2024-02-05 12:05:24 浏览: 25
如果您想要导出 WebView 中加载的文件,可以使用以下代码:
```
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
// 获取文件名
String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
// 下载文件
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(fileName);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}
});
```
这将在 WebView 加载需要下载的文件时,弹出下载提示框,并将文件保存到系统的下载文件夹中。请注意,如果您需要将文件保存到其他位置,可以更改 `setDestinationInExternalPublicDir` 方法调用的参数。
还需要注意的是,为了能够下载文件,您需要在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
```