[英]Downloading a pdf over blob link inside webview
I'm tring to download a pdf file inside a android web-view page.我正在尝试在 android web 视图页面中下载 pdf 文件。 The problem is that the Web-view don't support the blob-link.
问题是 Web 视图不支持 blob 链接。
So I made a JavaScript interface, suggest by this answer所以我做了一个 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();
}
But this don't work correctly, because when I load the url like:但这不能正常工作,因为当我加载网址时:
String newUrl = JavaScriptInterface.getBase64StringFromBlobUrl(url);
webView.loadUrl(newUrl);
nothing happining.什么都不开心。 So I suppose that is the blob url parse inside the interface, becouse when I change this: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true);"
所以我想这是接口内的 blob url 解析,因为当我改变这个时: "xhr.open('GET', '"+blobUrl.replace("blob:", "")+"', true); ” to this "xhr.open('GET', ' ', true);"
到这个“xhr.open('GET','', true);”
code works, but, obviusly, don't download the right pdf but a empty file.pdf.代码有效,但很明显,不要下载正确的 pdf,而是下载一个空的 file.pdf。
Any advice?有什么建议吗?
thanks谢谢
I had the same issue.我遇到过同样的问题。 In my case not all permissions were granted.
就我而言,并非所有权限都被授予。
Please check:请检查:
WRITE_EXTERNAL_STORAGE
, WRITE_EXTERNAL_STORAGE
,READ_EXTERNAL_STORAGE
and READ_EXTERNAL_STORAGE
和ACCESS_NOTIFICATION_POLICY
. ACCESS_NOTIFICATION_POLICY
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.