ItsT-Mo
ItsT-Mo

Reputation: 123

How do i set the download destination of my WebView to the Downloads folder without knowing the name of the file?

I have the following problem:

I have a WebView. This WebView has a download listener that acts when the user is trying to download a file.

I want the file to be downloaded to the regular "Downloads" folder. I can do this by using

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title);

But how do I save the file under its original name?

I can't use

String name = URLUtil.guessFileName(url, null, mimetype);

Since the url that is being called does not contain the filename.

My download manager currently looks like this:

mainWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            // Show a download notification
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            String title = URLUtil.guessFileName(url, null, mimetype);

            // Set directory of where the file should be saved to
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title);
            // Start the download
            dm.enqueue(request);
        }
}

Note: I am currently using the URLUtil.guessFilename() Method because that will allow me to save my file, event if it's under the wrong name.

Upvotes: 0

Views: 1231

Answers (1)

ItsT-Mo
ItsT-Mo

Reputation: 123

SOLUTION

The solution was passing the proper contentDisposition to the URLUtil.guessFileName() Function.

Getting the title works like this:

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

(All parameters are passed into the public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength))

Upvotes: 0

Related Questions