【问题标题】:Downloading a pdf over blob link inside webview通过 webview 中的 blob 链接下载 pdf
【发布时间】:2019-07-18 13:52:09
【问题描述】:

我正在尝试在 android web-view 页面中下载一个 pdf 文件。问题是 Web 视图不支持 blob-link。

所以我做了一个JavaScript接口,this answer建议

@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', '"+blobUrl.replace("blob:", "")+"', 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 {
    String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
    final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/report_" + 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())
        Toast.makeText(context, context.getApplicationContext().getString(R.string.download_success), Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context, context.getApplicationContext().getString(R.string.download_failed), Toast.LENGTH_LONG).show();

}

但这不能正常工作,因为当我加载网址时:

String newUrl = JavaScriptInterface.getBase64StringFromBlobUrl(url);
webView.loadUrl(newUrl);

没有任何事情发生。所以我想这是界面内的blob url解析,因为当我改变这个时: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);" 对此 "xhr.open('GET', ' ', true);"

代码有效,但很明显,下载的不是正确的 pdf,而是一个空的 file.pdf。

有什么建议吗?

谢谢

【问题讨论】:

    标签: javascript java android webview blob


    【解决方案1】:

    我有同样的问题。就我而言,并非所有权限都被授予。

    请检查:

    • WRITE_EXTERNAL_STORAGE,
    • READ_EXTERNAL_STORAGE
    • ACCESS_NOTIFICATION_POLICY

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2017-10-07
      • 2019-01-24
      • 2012-12-21
      相关资源
      最近更新 更多