Download Path of file from a website loaded in WebView Android

716 Views Asked by At

I am working on a project where use case is we have to load a web page url in webview which has a button when user clicks on button it will download pdf file. And we have to open that downloaded PDF. currently, i am not finding which path does the file got Downloaded.

1

There are 1 best solutions below

0
Pranav P Sreekumar On

You can use the webview download listener and set the path manually using DownloadManager.

An example where the file will be download to /Downloads folder would be:

myWebview.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);
        request.allowScanningByMediaScanner();
        String fileExtenstion = MimeTypeMap.getFileExtensionFromUrl(url);
        String filename = URLUtil.guessFileName(url, contentDisposition, fileExtenstion);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);
    }
});

Also add the below permissions to AndroidManifest.xml .

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>