从Android WebViewClient中的网站下载Blob文件

时间:2018-02-20 18:58:25

标签: javascript android android-webview blob

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

window.open(fileUrl);

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

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

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(),但行为是相同的。

2 个答案:

答案 0 :(得分:6)

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

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

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,这个类将有我们的脚本将在我们的网页中执行。

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

答案 1 :(得分:0)

对于stilll无法下载的用户。我稍微编辑了@Kevin方法: 将“您的BLOB URL转到此处”替换为blobUrl

    public static String getBase64StringFromBlobUrl(String blobUrl) {
        if (blobUrl.startsWith("blob")) {
            return "javascript: var xhr = new XMLHttpRequest();" +
                    "xhr.open('GET', '" + blobUrl + "', 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');";
    }