繁体   English   中英

通过 webview 中的 blob 链接下载 pdf

[英]Downloading a pdf over blob link inside webview

我正在尝试在 android web 视图页面中下载 pdf 文件。 问题是 Web 视图不支持 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();

}

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

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

什么都不开心。 所以我想这是接口内的 blob url 解析,因为当我改变这个时: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true); ” 到这个“xhr.open('GET','', true);”

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

有什么建议吗?

谢谢

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

请检查:

  • WRITE_EXTERNAL_STORAGE ,
  • READ_EXTERNAL_STORAGE
  • ACCESS_NOTIFICATION_POLICY

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM