我正在尝试在Android WebView页面内下载PDF文件。问题在于WebView不支持Blob链接。
因此,我创建了一个JavaScript接口,根据这个答案的建议。
但是这样做并不正确,因为当我加载像这样的URL时:
因此,我创建了一个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。
有什么建议吗?
谢谢