在Webview内通过Blob链接下载pdf

时间:2019-07-18 13:52:09

标签: javascript java android webview blob

我正打算在android网络视图页面中下载pdf文件。问题在于Web视图不支持Blob链接。

所以我做了一个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网址解析,因为更改此代码时:      “” xhr.open('GET','“ + blobUrl.replace(” blob:“,”“)+”',true);“ 对此      “ xhr.open('GET','',true);”

代码有效,但是很明显,请不要下载正确的pdf,而要下载一个空文件。

有什么建议吗?

谢谢

1 个答案:

答案 0 :(得分:0)

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

请检查:

  • WRITE_EXTERNAL_STORAGE
  • READ_EXTERNAL_STORAGE
  • ACCESS_NOTIFICATION_POLICY
相关问题