简体   繁体   English

在android webview中下载文件(pdf,ppt,xls)以下载没有浏览器的文件夹

[英]Download files (pdf , ppt , xls) in android webview to download folder without browser

I am developing an app that has a webview in it and inside the webiste displayed there are some pdf , xls and ppt files that have to be downloaded once touched (onclick).Now how do I do this , because I tried some approaches here from stackoverflow but none of them worked.I know I have to use download manager to download them, and I dont need to display them in my app just to download them. 我正在开发一个带有Web视图的应用程序,显示的Webist内部有一些pdf,xls和ppt文件,一旦触摸(onclick)就必须下载。现在我该怎么做,因为我尝试了一些方法stackoverflow但它们都不起作用。我知道我必须使用下载管理器来下载它们,并且我不需要在我的应用程序中显示它们就可以下载它们。 Here is the code that I use to display my webview and a screenshot of one of the pages that contains the files. 这是我用来显示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();
                    }
                }
            });

在此处输入图片说明

EDIT 2 编辑2

OK @zepar , I followed your instructions and I get this exception.What could be the problem: 好的@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)

You can extend WebViewClient and override shouldOverrideUrlLoading method. 您可以扩展WebViewClient并重写shouldOverrideUrlLoading方法。 In the method you are able to check if you want to handle the request or leave it for WebView . 在方法中,您可以检查是否要处理请求或将其留给WebView

see the android documentation 请参阅android文档

EDIT 编辑

referring to the comment below, here is the example: 参考下面的注释,这里是示例:

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

and set an instance of the class to your WebView: 并将该类的实例设置为您的WebView:

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

EDIT2 EDIT2

The easiest way to download files is to use AsyncTask : 下载文件的最简单方法是使用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;
    }
}

to download file you have to execute the task with url as an argument: 要下载文件,您必须以url作为参数执行任务:

new DownloadTask().execute(url);

EDIT3 EDIT3

I guess, it is because the path does not exist or is invalid. 我猜是因为该路径不存在或无效。 Try introduce few changes: the first thing is the filename, where I assume the url would look like this: http://host/file.pdf not as argument of php. 尝试引入一些更改:第一件事是文件名,我假设url看起来像这样: http://host/file.pdf而不是php的参数。 This is not proper way for that, but you can try this: 这不是正确的方法,但是您可以尝试以下方法:

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

and

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

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

相关问题 Android Webview下载并查看pdf,xls或doc文件 - Android webview download and view pdf, xls or doc files Android Webview 下载管理器下载 PDF 文件 - Android Webview Download manager To Download PDF Files 如何在Web视图中使用下载管理器将pdf / ppt / doc文件下载到sdcard - How to use a download Manager in a webview to download pdf/ppt/doc files to sdcard 使用Android Webview下载文件 - Download files with Android Webview 使用phonegap在android和ios中读取pdf,doc,ppt和xls文件 - Reading Pdf, Doc, Ppt and xls files in android and ios using phonegap 下载一个 PDF 到 android 设备下载文件夹 Android - Download a PDF into android device download folder Android Android webview无法下载文件 - Android webview cannot download files 在 Android 浏览器中 PDF 下载失败 - PDF download fails in Android Browser 从 URL 下载 pdf 文件并将其保存在 android (java) 中的特定文件夹中 - Download pdf files from URL and save it in a particular folder in android (java) 我无法显示ppt实际上,我不仅要在视图中显示ppt,还要显示doc / ppt / pdf / xls文件…在android中 - Iam not able to display the ppt infact i want to display not only ppt but also doc/ppt/pdf/xls files in a view… in android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM