无法将图像接收为blob

时间:2018-01-19 10:07:51

标签: javascript android webview blob

我正在尝试读取包含图像的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 。然后我注入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文件,但没有图像。

1 个答案:

答案 0 :(得分:2)

使用以下Javascript字符串从blob对象获取图像/ PDF。 Javascript参考。代码取自this

 List<String> nameList   = new ArrayList<>(
            Arrays.asList("USA", "USSR", "UK"));

 nameList.forEach((v) -> System.out.println(v));