简体   繁体   English

Android webview无法下载文件

[英]Android webview cannot download files

i am working with one HTML application.我正在使用一个 HTML 应用程序。 which i had browse in webview now that site will allow to download PDF file.我已经在 webview 中浏览了,现在该站点将允许下载 PDF 文件。
Now issue is that when load that URL in device browser it will download PDF file automaticaly but in webview cannot download that file i had used below code.现在的问题是,当在设备浏览器中加载该 URL 时,它会自动下载 PDF 文件,但在 webview 中无法下载我在下面代码中使用过的那个文件。

webView.setWebViewClient(new Callback());
webView.setWebChromeClient(new webChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSavePassword(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.getSettings().setSupportMultipleWindows(false);
webView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimetype,long contentLength) {
          AppLog.logString(TAG+"setDownloadListener");
          AppLog.logString(TAG+"url: "+url);
          //Intent intent = new Intent(Intent.ACTION_VIEW);
          //intent.setData(Uri.parse(url));
          //startActivity(intent);
        }
    });
    webView.loadUrl(url);

private class Callback extends WebViewClient{  
    String TAG="ClBk: ";
    @SuppressWarnings("unused")
    @SuppressLint("DefaultLocale")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        AppLog.logString(TAG+"shouldOverrideUrlLoading");
        AppLog.logString(TAG+"url: "+url);

        if(!isInternetOncheck()){
            intenetDialog();
        }else{

            boolean value = true;  
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);  
            AppLog.logString(TAG+"extension: "+extension);
            if (extension != null) {  
                 MimeTypeMap mime = MimeTypeMap.getSingleton();  
                 String mimeType = mime.getMimeTypeFromExtension(extension);
                 AppLog.logString(TAG+"mimeType: "+mimeType);
                 if (mimeType != null) {  
                      if (mimeType.contains("application/zip")
                                ||mimeType.toLowerCase().contains("video")  
                                || extension.toLowerCase().contains("mov")  
                                || extension.toLowerCase().contains("mp3")) {
                           AppLog.logString(TAG+"If MimeType for dowloading");
                           DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);  
                           DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));  
                           File destinationFile = new File(Environment.getExternalStorageDirectory(),getFileName(url,extension));  
                           request.setDescription("Downloading via Your app name..");  
                           request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
                           request.setDestinationUri(Uri.fromFile(destinationFile));  
                           mdDownloadManager.enqueue(request);  
                           value = false;  
                      }  
                 }  
            }  
            if(url.contains(".pdf")){
            AppLog.logString(TAG+"pdf");
            view.setDownloadListener(new DownloadListener() {
                @SuppressLint("NewApi")
                public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimetype, long contentLength) {
                    AppLog.logString(TAG+"download pdf");
                    startDownloadPDF(url);
                }
            });
            }else if(url.contains(".rar")){
                AppLog.logString(TAG+"rar");
                view.setDownloadListener(new DownloadListener() {
                    @SuppressLint("NewApi")
                    public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimetype, long contentLength) {
                        AppLog.logString(TAG+"download rar");
                        startDownloadZBS(url);
                    }
                });
            }else{
                AppLog.logString(TAG+"else: "+url);
            }
            progressBar.setVisibility(View.VISIBLE);
            view.loadUrl(url);
            return true;
        }
        return true;
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        AppLog.logString(TAG+"onPageStarted");
        //AppLog.logString(TAG+"url: "+url);
        progressBar.setVisibility(View.VISIBLE);
        if(!isInternetOncheck()){
            intenetDialog();
        }
        super.onPageStarted(view, url, favicon);
    }   
    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        AppLog.logString(TAG+"onPageFinished");
        //AppLog.logString(TAG+"url: "+url);
        progressBar.setVisibility(View.INVISIBLE);
        webView.setVisibility(View.VISIBLE);
        ((RelativeLayout)findViewById(R.id.layoutSplace)).setVisibility(View.GONE);
        super.onPageFinished(view, url);
    }   
 }

In browser when url dowload pdf file it dowloading in this url (http:/......../rptTrialBalance/ExporttoPDF?dtSession1=PDFReport&FileName=TrialBa‌​lance&download=true) in browser it download but webview cannot download this在浏览器中,当 url 下载 pdf 文件时,它会在浏览器中下载此 url (http:/......../rptTrialBalance/ExporttoPDF?dtSession1=PDFReport&FileName=TrialBa‌​lance&download=true),但 webview 无法下载此文件

i had already check this url it's not working How to use a download Manager in a webview to download pdf/ppt/doc files to sdcard我已经检查过这个 url 它不起作用如何在 webview 中使用下载管理器将 pdf/ppt/doc 文件下载到 sdcard

I think you need to use Chrome CLient for this.我认为您需要为此使用 Chrome 客户端。

//webExternalLinks is your webview.

    webExternalLinks.setWebChromeClient(new WebChromeClient() {
                public void onProgressChanged(WebView view, int progress) {
                    if(seekBar==null){
                        seekBar = IjoomerUtilities
                                .getLoadingDialog(getString(R.string.dialog_loading_please_wait));
                    }
                    seekBar.setProgress(progress);
                    if(progress==100){
                        seekBar=null;
                    }
                }
            });

            webExternalLinks.setWebViewClient(new WebViewClient());
            webExternalLinks.getSettings().setJavaScriptEnabled(true);
            webExternalLinks.getSettings().setPluginState(PluginState.ON);
            webExternalLinks.getSettings().setSupportZoom(true);
            webExternalLinks.getSettings().setBuiltInZoomControls(true);

            if (link != null && link.length() > 0) {
                if (!link.startsWith("http://") && !link.startsWith("https://")) {
                    link = "http://" + link;
                }
                webExternalLinks.loadUrl(link);
            }
mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype,
                long contentLength) {
          Intent i = new Intent(Intent.ACTION_VIEW);
          i.setData(Uri.parse(url));
          startActivity(i);
        }
    });

try this one: first of all ,plz print Url which you passed in URI.and open that URL in Browser.is it open or not?试试这个:首先,请打印您在 URI 中传递的 URL。然后在浏览器中打开该 URL。它是否打开? if it is not open in browswer then problem getting url.如果它没有在浏览器中打开,那么获取 url 有问题。

From a breif looking, you don't identify the pdf download as your condition is url.contains(".pdf") but your URL doesn't contain this string.从 breif 看,您没有识别 pdf 下载,因为您的条件是 url.contains(".pdf") 但您的 URL 不包含此字符串。 you should somehow get the content type returned in the response header content-type.您应该以某种方式获取响应标头内容类型中返回的内容类型。 Hope that helps.希望有帮助。 Nitzan日山

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM