【问题标题】:Download files (pdf , ppt , xls) in android webview to download folder without browser在android webview中下载文件(pdf,ppt,xls)以在没有浏览器的情况下下载文件夹
【发布时间】:2015-04-18 13:07:02
【问题描述】:

我正在开发一个包含 webview 的应用程序,并且在显示的网站内有一些 pdf 、 xls 和 ppt 文件,一旦触摸(onclick)就必须下载。现在我该怎么做,因为我尝试了一些来自stackoverflow的方法,但它们都不起作用。我知道我必须使用下载管理器来下载它们,我不需要在我的应用程序中显示它们只是为了下载它们。 这是我用来显示我的 web 视图的代码和包含这些文件的页面之一的屏幕截图。

        //Load webview
            moodleweb = (WebView) findViewById(R.id.moodlewebview);
            moodleweb.setWebViewClient(new WebViewClient());
            WebSettings webSettings = moodleweb.getSettings();
            webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
            moodleweb.loadUrl("http://moodle.ubt-uni.net/");
            webSettings.setJavaScriptEnabled(true);
moodleweb.getSettings().setCacheMode(moodleweb.getSettings().LOAD_DEFAULT);
            moodleweb.getSettings().setAppCacheEnabled(true);
            moodleweb.clearCache(false);
            moodleweb.setWebChromeClient(new WebChromeClient(){
    
                public void onProgressChanged(WebView view, int progress) {
    
                    progressBar.setProgress(progress);
                    if(progress == 100) {
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });![enter image description here][2]
            backbutton = (Button) findViewById(R.id.backbutton);  
            backbutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(moodleweb.canGoBack()){
                        moodleweb.goBack();
                    }else{
                        finish();
                    }
                }
            });

编辑 2

好的 @zepar ,我按照你的指示操作,我得到了这个异常。可能是什么问题:

02-18 12:27:51.943    4972-5424/net.prdev.ubtsmismoodle E/MoodleActivity﹕ 
Exception:
    java.io.FileNotFoundException: /sdcard/downloadedFiels/pluginfile.php?file=%2F23496%2Fmod_resource%2Fcontent%2F1%2FOrari%20i%20transportit%20t%C3%AB%20studenteve%20Prizren%20-%20Prishtin%C3%AB%20dhe%20anasjelltas.pdf: open failed: ENOENT (No such file or directory)
            at libcore.io.IoBridge.open(IoBridge.java:456)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:145)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:125)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
            at libcore.io.Posix.open(Native Method)
            at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
            at libcore.io.IoBridge.open(IoBridge.java:442)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:145)
            at net.prdev.ubtsmismoodle.MoodleActivity$DownloadTask.doInBackground(MoodleActivity.java:125)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

【问题讨论】:

    标签: android pdf webview download android-download-manager


    【解决方案1】:

    您可以扩展 WebViewClient 并覆盖 shouldOverrideUrlLoading 方法。在该方法中,您可以检查是否要处理请求或将其留给WebView。

    see the android documentation

    编辑

    参考下面的评论,这里是例子:

    public class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.endsWith(".pdf") || url.endsWith(".xls") || url.endsWith(".ppt")) {
                Log.i(TAG, "download: " + url);
                // In this place you should handle the download
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }
    

    并将该类的实例设置为您的 WebView:

    moodleweb.setWebViewClient(new MyWebViewClient());
    moodleweb.loadUrl("http://moodle.ubt-uni.net/");
    

    EDIT2

    下载文件最简单的方法是使用AsyncTask:

    private class DownloadTask extends AsyncTask<String, Void, Void> {
    
        @Override
        protected Void doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                String filename = url.getFile();
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
    
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Server didn't return 200. ");
                    // handle error
                    return null;
                }
    
                input = connection.getInputStream();
                output = new FileOutputStream("/sdcard/downloadedFiels/" + filename); // where to save file
    
                byte data[] = new byte[4096];
                int count;
                while ((count = input.read(data)) != -1) {
                    if (isCancelled()) {
                        return null;
                    }
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                // handle error
                Log.e(TAG, "Exception: ", e);
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException e) {
                    Log.e(TAG, "IOException: ", e);
                }
    
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }
    }
    

    要下载文件,您必须使用 url 作为参数执行任务:

    new DownloadTask().execute(url);
    

    EDIT3

    我猜,是因为路径不存在或无效。尝试引入一些更改: 首先是文件名,我假设 url 看起来像这样:http://host/file.pdf 不是 php 的参数。这不是正确的方法,但你可以试试这个:

    String filename = URLDecoder.decode(sUrl[0].substring(sUrl[0].lastIndexOf("=")), "UTF-8");
    

    和

    // where to save file
    File file = new File("/sdcard/downloadedFiels/" + filename);
    file.mkdirs();
    output = new FileOutputStream(file);
    

    【讨论】:

    • 是的,我明白了,问题是我已经尝试了多次都没有成功,所以如果你能帮助我,一些代码 sn-p 或整个工作代码会非常好;)
    • 好的,谢谢,现在我只需要弄清楚如何下载文件并将代码放入 shouldOverrideUrlLoading 方法中。如果您能帮我解决这个问题,我将不胜感激。
    • 您可以创建一种下载管理器来管理下载。但下载文件最简单的方法是使用AsyncTask。看看我的EDIT2。
    • 非常感谢,在我的问题中,我添加了一个 EDIT 2 标头,并在那里发布了我在执行您的代码时遇到的异常。如果您能看一下就好了。
    猜你喜欢
    • 2013-03-22
    • 1970-01-01
    • 2016-01-20
    • 2016-03-26
    • 2013-04-30
    • 2021-12-26
    • 2018-05-15
    • 2014-03-27
    相关资源
    最近更新 更多