下载 WebView 中的文件

我在 Android 应用程序中有一个 webview。当用户转到 webview 并单击一个链接下载一个文件时,什么也没有发生。

URL = "my url";
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);
mWebView.loadUrl(URL);
Log.v("TheURL", URL);

如何在 webview 中启用下载?如果我禁用了 webview,并启用了从应用程序加载浏览器 URL 的意图,那么下载工作就是无缝的。

String url = "my url";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

有人能帮帮我吗?页面加载没有问题,但链接到 HTML 页面中的图像文件不工作..。

181405 次浏览

Have you tried?

mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});

Example Link: Webview File Download - Thanks @c49

Try using download manager, which can help you download everything you want and save you time.

Check those to options:

Option 1 ->

 mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);


}
});

Option 2 ->

if(mWebview.getUrl().contains(".mp3") {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);


}

Try this out. After going through a lot of posts and forums, I found this.

mWebView.setDownloadListener(new DownloadListener() {


@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));


request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();


}
});

Do not forget to give this permission! This is very important! Add this in your Manifest file(The AndroidManifest.xml file)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <!-- for your file, say a pdf to work -->

Hope this helps. Cheers :)

    mwebView.setDownloadListener(new DownloadListener()
{


@Override




public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {


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(URLUtil.guessFileName(url, contentDisposition,
mimeType));




request.allowScanningByMediaScanner();




request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}});
webView.setDownloadListener(new DownloadListener()
{
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
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(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});

If you don't want to use a download manager then you can use this code

webView.setDownloadListener(new DownloadListener() {


@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition
, String mimetype, long contentLength) {


String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);


try {
String address = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ Environment.DIRECTORY_DOWNLOADS + "/" +
fileName;
File file = new File(address);
boolean a = file.createNewFile();


URL link = new URL(url);
downloadFile(link, address);


} catch (Exception e) {
e.printStackTrace();
}
}
});


public void downloadFile(URL url, String outputFileName) throws IOException {


try (InputStream in = url.openStream();
ReadableByteChannel rbc = Channels.newChannel(in);
FileOutputStream fos = new FileOutputStream(outputFileName)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
// do your work here


}

This will download files in the downloads folder in phone storage. You can use threads if you want to download that in the background (use thread.alive() and timer class to know the download is complete or not). This is useful when we download small files, as you can do the next task just after the download.