从Android WebViewClient中的网站下载Blob文件 [英] Download Blob file from Website inside Android WebViewClient

查看:1301
本文介绍了从Android WebViewClient中的网站下载Blob文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML网页,其中有一个按钮,当用户点击时会触发POST请求。请求完成后,将触发以下代码:

I have an HTML Web page with a button that triggers a POST request when the user clicks on. When the request is done, the following code is fired:

window.open(fileUrl);

浏览器中的一切都很好用,但是当在Webview组件内部实现时,新选项卡不会打开了。

Everything works great in the browser, but when implement that inside of a Webview Component, the new tab doesn't is opened.

仅供参考:在我的Android应用程序中,我设置了以下内容:

FYI: On my Android App, I have set the followings things:

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

AndroidManifest.xml 我有以下权限:

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

我也尝试用 setDownloadListener 来捕获下载。另一种方法是将 WebViewClient()替换为 WebChromeClient(),但行为是相同的。

I try too with a setDownloadListener to catch the download. Another approach was replaced the WebViewClient() for WebChromeClient() but the behavior was the same.

推荐答案

好的我在使用webview时遇到了同样的问题,我意识到WebViewClient无法像Chrome桌面客户端那样加载blob URL,我解决了它使用Javascript接口。您可以按照以下步骤执行此操作,在此应用程序中使用minSdkVersion正常工作:17。首先,通过JS转换Base64字符串中的Blob URL数据。其次,将此字符串发送到Java类,最后以可用格式转换它,在这种情况下,我将其转换为.pdf文件。

Ok I had the same problem working with webviews, I realized that WebViewClient can't load "blob URLs" as Chrome Desktop client does, I solved it using Javascript Interfaces. You can do this following these steps, is working fine in this app with minSdkVersion: 17. First, transform the Blob URL data in Base64 string trough a JS. Second, send this string to a Java Class and finally convert it in an available format, in this case I converted it in a ".pdf" file.

首先要做的事情。您必须设置您的webview,在我的情况下,我正在加载片段中的网页:

First things first. You have to setup your webview, in my case I'm loading the webpages in a fragment:

public class WebviewFragment extends Fragment {
    WebView browser;
    ...

    // invoke this method after set your WebViewClient and ChromeClient
    private void browserSettings() {
        browser.getSettings().setJavaScriptEnabled(true);
        browser.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                browser.loadUrl(JavaScriptInterface.getBase64StringFromBlobUrl(url));
            }
        });
        browser.getSettings().setAppCachePath(getActivity().getApplicationContext().getCacheDir().getAbsolutePath());
        browser.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        browser.getSettings().setDatabaseEnabled(true);
        browser.getSettings().setDomStorageEnabled(true);
        browser.getSettings().setUseWideViewPort(true);
        browser.getSettings().setLoadWithOverviewMode(true);
        browser.addJavascriptInterface(new JavaScriptInterface(getContext()), "Android");
        browser.getSettings().setPluginState(PluginState.ON);
    }
}

有了这个,让我们创建一个JavaScriptInterface.class,这个class将有我们的脚本将在我们的网页上执行。

Having this, lets create a JavaScriptInterface.class, this class will have our script who is going to be executed in our webpage.

public class JavaScriptInterface {
    private Context context;
    private NotificationManager nm;
    public JavaScriptInterface(Context context) {
        this.context = context;
    }

    @JavascriptInterface
    public void getBase64FromBlobData(String base64Data) throws IOException {
        convertBase64StringToPdfAndStoreIt(base64Data);
    }
    public static String getBase64StringFromBlobUrl(String blobUrl){
       if(blobUrl.startsWith("blob")){
           return "javascript: var xhr = new XMLHttpRequest();" +
                    "xhr.open('GET', 'YOUR BLOB URL GOES HERE', true);" +
                    "xhr.setRequestHeader('Content-type','application/pdf');" +
                    "xhr.responseType = 'blob';" +
                    "xhr.onload = function(e) {" +
                    "    if (this.status == 200) {" +
                    "        var blobPdf = this.response;" +
                    "        var reader = new FileReader();" +
                    "        reader.readAsDataURL(blobPdf);" +
                    "        reader.onloadend = function() {" +
                    "            base64data = reader.result;" +
                    "            Android.getBase64FromBlobData(base64data);" +
                    "        }" +
                    "    }" +
                    "};" +
                    "xhr.send();";
        }
        return "javascript: console.log('It is not a Blob URL');";
    }
    private void convertBase64StringToPdfAndStoreIt(String base64PDf) throws IOException {
        final int notificationId = 1;
        String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
        final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS) + "/YourFileName_" + currentDateTime + "_.pdf");
        byte[] pdfAsBytes = Base64.decode(base64PDf.replaceFirst("^data:application/pdf;base64,", ""), 0);
        FileOutputStream os;
        os = new FileOutputStream(dwldsPath, false);
        os.write(pdfAsBytes);
        os.flush();

        if(dwldsPath.exists()) {
            NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MY_DL");
                    .setDefaults(NotificationCompat.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_file_download_24dp)
                    .setContentTitle("MY TITLE")
                    .setContentText("MY TEXT CONTENT");
            nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
            if(nm != null) {
                nm.notify(notificationId, b.build());
                Handler h = new Handler();
                long delayInMilliseconds = 5000;
                h.postDelayed(new Runnable() {
                    public void run() {
                        nm.cancel(notificationId);
                    }
                }, delayInMilliseconds);
            }
        }
    }
}

来源:

https://stackoverflow.com/a/41339946/4001198

https://stackoverflow.com/a/11901662/ 4001198

https://stackoverflow.com/a/ 19959041/4001198

这篇关于从Android WebViewClient中的网站下载Blob文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆