0

I want to be able to download a file through Android's webview but I cannot do it.

The url I have to download from is in this format:

http://{server_path}/Download?mimetype=application/octet-stream

I am using this code:

myWebView.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));

    request.setMimeType(mimetype);
    //------------------------COOKIE!!------------------------
    String cookies = CookieManager.getInstance().getCookie(url);
    request.addRequestHeader("cookie", cookies);
    //------------------------COOKIE!!------------------------
    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);
    long donwloadedFileId = dm.enqueue(request);
    String downloadedMimeType = dm.getMimeTypeForDownloadedFile(donwloadedFileId)
    Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
  }
});


When I try to download all I get is a "download.bin" file.

As I check the function URLUtil.guessFileName(url, contentDisposition, mimetype) returns this as a file name.

Could you help me?

EDIT

If I rename the downloaded file from Android File manager app, it opens succefully. So maybe the answer is how can I set the correctly mimeType of the downloaded file?

EDIT 2 (13/4/20)

Also I forgot to mention that in the above code mimeType is "application/octet-stream"

2 Answers2

1

@Net Here is the debug output:

this = {MainActivity$1@10423} 
url = "http://{server_path}/Download?mimetype=application/octet-stream"
userAgent = "Mozilla/5.0 (Linux; Android 10; Android SDK built for x86 Build/QSR1.191030.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.185 Mobile Safari/537.36"
contentDisposition = "attachment; filename*=UTF-8''M1FBACTFMB9F.pdf"
mimetype = "application/octet-stream"
contentLength = 192748
request = {DownloadManager$Request@10430} 
dm = {DownloadManager@10432} 
0

You can try to do this with your file:

File file = new File(yourFileHere);
mimeType= URLConnection.guessContentTypeFromName(file.getName());

or try

Files.probeContentType(path)

EDIT

Add the next header to your request:

"content-disposition", "attachment; filename=\"" + fileName +"\""
Ner
  • 104
  • 6