如何获取文件名以将其放置在webview DownloadListener中的下载文件中

问题描述 投票:0回答:3

我有一个webview应用,它用于我的本地网站So ..

[当我单击链接下载任何文件时,它是在下载文件,但具有“文件名”名称,就像我在代码中选择的一样!。

所以有什么方法可以获取要下载的文件名,将其设置为下载名。

[请编辑我的代码并将其粘贴给我,因为我是Android编程的初学者。

这是我的DownloadListener代码

谢谢大家^ _ ^。

webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url,String userAgent,String contentDisposition,String type,long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "File Name");
                DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (manager != null) {
                    manager.enqueue(request);
                    Toast.makeText(getApplicationContext(), "بدأ التحميل ...", Toast.LENGTH_LONG).show();
                }
            }
        });

    }
java android webview
3个回答
1
投票

您是否尝试在Content-Disposition标头中设置文件名? https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

类似于request.addRequestHeader("Content-Disposition", "attachment; filename=\"filename.txt\"");


1
投票

如果是Get url。文件名将是url的结尾。

如果是POST方法。文件名将在响应头中商定。

希望能帮助您。


0
投票

我找到了执行我所需要的代码,谢谢大家

我希望能帮助一些人。

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);
                //------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                //------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("بدأ تحميل الملف...");
                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(), "بدأ تحميل الملف...", Toast.LENGTH_LONG).show();
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.