最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download file in Webview - Stack Overflow

programmeradmin0浏览0评论

I'm using webview in an Android application. I am trying to download a .pdf file, however when the link is clicked through the application the .pdf file name is changed to "1rcPnhg9_rSes92BiQPotVjXuEAfFnyrf.pdf", and is not saved with the original file name.

How to make webview save the file with the original name? At the moment the webview is saving the file using the ID as the name.

Used link: ;id=1rcPnhg9_rSes92BiQPotVjXuEAfFnyrf

WebView:

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();
            }});

Permissions in Manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>

I'm using webview in an Android application. I am trying to download a .pdf file, however when the link is clicked through the application the .pdf file name is changed to "1rcPnhg9_rSes92BiQPotVjXuEAfFnyrf.pdf", and is not saved with the original file name.

How to make webview save the file with the original name? At the moment the webview is saving the file using the ID as the name.

Used link: https://drive.google./uc?export=download&id=1rcPnhg9_rSes92BiQPotVjXuEAfFnyrf

WebView:

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();
            }});

Permissions in Manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
Share Improve this question edited Mar 15, 2022 at 14:55 Maria Fernanda asked Mar 15, 2022 at 14:25 Maria FernandaMaria Fernanda 612 silver badges6 bronze badges 1
  • URLUtil.guessFileName doesn't ask the document for a file name, but tries to guess the file name from just the URL. If the file name you want isn't in the URL, it's not going to get there. You'll need to supply the file name from elsewhere. – drdaanger Commented Mar 15, 2022 at 15:59
Add a ment  | 

3 Answers 3

Reset to default 3

Here a test with your link (in Kotlin). If you need a Java example, please, let me know:

private fun test() {
    webView = findViewById(R.id.webView)

    webView.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            Log.d(TAG, "shouldOverrideUrlLoading:url = ${url}")
            if (url.contains("=download")){
                Log.d(TAG, "shouldOverrideUrlLoading: ")
                downloadFile(url)
                webView.stopLoading()
            }
            return true
        }
    }
    val url = "https://drive.google./uc?export=download&id=1rcPnhg9_rSes92BiQPotVjXuEAfFnyrf"
    webView.loadUrl(url)
}

fun downloadFile(url: String) {
    Log.d(TAG, "downloadFile: url = $url")
    val manager = getSystemService(Activity.DOWNLOAD_SERVICE) as DownloadManager
    val uri =
        Uri.parse(url)
    val request = DownloadManager.Request(uri)
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    val reference: Long = manager.enqueue(request)
}

image abuot download

Java code:

    private void test() {

    webView = findViewById(R.id.webView);

    webView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.contains("=download")){
                downloadFile(url);
            }

            return super.shouldOverrideUrlLoading(view, url);
        }
    });

    String url = "https://drive.google./uc?export=download&id=1rcPnhg9_rSes92BiQPotVjXuEAfFnyrf";
    webView.loadUrl(url);
}

private void downloadFile(String url) {
    DownloadManager manager = (DownloadManager) getSystemService(Activity.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    manager.enqueue(request);
}

An option to use DownloadManager

For this you sould add an onNavigating event to your WebView. If the user target a pdf file you can stop the loading process with: ags.Cancel = true And this point when you can pass the url to a DownloadManager what will download your file.

Here a simple code

webView.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            if (url.contains(".pdf")){
                downloadFile(url)
            }
            return false
        }
    }

    fun downloadFile(url: String) {
    Log.d(TAG, "downloadFile: url = $url")
    val manager = getSystemService(Activity.DOWNLOAD_SERVICE) as DownloadManager
    val uri =
        Uri.parse(url)
    val request = DownloadManager.Request(uri)
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    val reference: Long = manager.enqueue(request)
}
发布评论

评论列表(0)

  1. 暂无评论