我正在尝试读取包含图像的 blob。我可以从下面的代码中读取 PDF:
web.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
CommonUtilities._Log(TAG, "url = " + url + " ,, userAgent = " + userAgent + " ,,contentDisposition " + contentDisposition + " ,, mimetype = " + mimetype + " ,, length= " + contentLength);
String s = "var request = new XMLHttpRequest();\n" +
"request.open(\'GET\', \"" + url + "\", true);\n" +
"request.responseType = \'blob\';\n" +
"request.timeout = 30000;" +
"request.onload = function() {\n" +
" var reader = new FileReader();\n" +
" reader.readAsDataURL(request.response); \n" +
" reader.onloadend = function() {\n" +
" base64data = reader.result; \n" +
" // console.log(base64data);\n" +
" Android.androidPay(base64data)" +
" }\n" +
"\n" +
"};\n" +
"request.send();";
WebLink.this.web.evaluateJavascript(s, new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
CommonUtilities._Log(TAG, "value " + value);
}
});
}
});
在 onDownloadStart 方法中,我可以接收到一个 blob。然后我注入(inject) Javascript 代码来获取 blob 数据。 Android.androidPay(base64data) 接收字符串数据。
private void writeToSDFile(String string, String fileName) {
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS);
dir.mkdirs();
File file = new File(dir, fileName);
try {
byte[] data = android.util.Base64.decode(string, Base64.DEFAULT);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(data);
bos.flush();
bos.close();
CommonUtilities._Log(TAG, "File Path " + file.getCanonicalPath());
CommonUtilities.showFolderIntent(this, dir);
} catch (Exception e) {
CommonUtilities._Log(TAG, Log.getStackTraceString(e));
}
}
我使用上述方法将数据写入新文件。我已针对此问题尝试了多种解决方案,但无法解决错误。使用这种方法,我只能接收 PDF 文件,但不能接收图像。
最佳答案
使用以下 Javascript 字符串从 blob 对象获取图像/PDF。 Javascript 引用。代码取自 this
String s ="var xhr = new XMLHttpRequest();\n"+
"xhr.open(\'GET\', \"" + url + "\", true);\n"+
"\n"+
"xhr.responseType = \'arraybuffer\';\n"+
"\n"+
"xhr.onload = function(e) {\n"+
" if (this.status == 200) {\n"+
" var uInt8Array = new Uint8Array(this.response);\n"+
" var i = uInt8Array.length;\n"+
" var binaryString = new Array(i);\n"+
" while (i--)\n"+
" {\n"+
" binaryString[i] = String.fromCharCode(uInt8Array[i]);\n"+
" }\n"+
" var data = binaryString.join(\'\');\n"+
"\n"+
" var base64 = window.btoa(data);\n"+
"\n"+
" Android.androidPay(base64)" +
" }\n"+
"};\n"+
"\n"+
"xhr.send();";
关于javascript - 无法将图像接收为 blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48338570/