我正在尝试在 Android 网页 View 页面中下载 pdf 文件。问题是 Web View 不支持 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 url 解析,因为当我更改它时: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);" 对此 "xhr.open('GET', ' ', true);"
代码可以工作,但是,显然,不要下载正确的 pdf,而是下载空的 file.pdf。
有什么建议吗?
谢谢
最佳答案
我也遇到了同样的问题。就我而言,并非所有权限都被授予。
请检查:
WRITE_EXTERNAL_STORAGE
,READ_EXTERNAL_STORAGE
和ACCESS_NOTIFICATION_POLICY
。
关于javascript - 通过 webview 内的 blob 链接下载 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57096149/