在Webview中通过Blob链接下载PDF

3
我正在尝试在Android WebView页面内下载PDF文件。问题在于WebView不支持Blob链接。
因此,我创建了一个JavaScript接口,根据这个答案的建议。
@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();

}

但是这样做并不正确,因为当我加载像这样的URL时:
String newUrl = JavaScriptInterface.getBase64StringFromBlobUrl(url);
webView.loadUrl(newUrl);

什么都没有发生。所以我想这是界面内部的Blob URL解析,因为当我将这个: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);" 改成这个 "xhr.open('GET', ' ', true);"

代码可以运行,但显然不能下载正确的PDF而是一个空的file.pdf。

有什么建议吗?

谢谢


1
遇到相同的问题,有解决方案吗? - jagadishlakkurcom jagadishlakk
1个回答

0

我遇到了同样的问题。在我的情况下,没有授予所有许可权限。

请检查:

  • WRITE_EXTERNAL_STORAGE
  • READ_EXTERNAL_STORAGE
  • ACCESS_NOTIFICATION_POLICY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接