Liuting
Liuting

Reputation: 1108

Android Webview shouldOverrideUrlLoading() is not called for base64 image data URL

In my WebView it loads a webpage that includes a link to download an image with base64 data:

<a href="data:image/jpeg;base64,{base64data}" download="fileName.jpg" target="_blank">Download Image</a>

In Chrome when it's clicked, it will download the image as a JPG file. But it doesn't work in Android WebView.

Download Images using android webview indicates that I should use shouldOverrideUrlLoading() to trigger the download.

It works with the image URL like http://.../image.jpg. But for my base 64 data URL, it only works on Android versions below 4.4, the method shouldOverrideUrlLoading() is never called on Android 4.4+ because it has to be a valid URL according to the Android API Guides.

So my question is, why data:image/jpeg;base64,{base64data} is not a valid URL in this case? What should I do to trigger shouldOverrideUrlLoading() for the base64 data URL? (Or even by making changes on the webpage)

Any suggestions would be highly appreciated, all I need is to save the image in Android.

Upvotes: 3

Views: 1405

Answers (1)

Mikhail Naganov
Mikhail Naganov

Reputation: 6871

If you need to trigger shouldOverrideUrlLoading for your data: URI, simply remove the download="fileName.jpg" target="_blank" part from your <a> tag.

Actually, it's the download attribute that prevents shouldOverrideUrlLoading from being called, but having target="_blank" doesn't help anything, so it should be removed, too. You just need to return true from shouldOverrideUrlLoading to avoid WebView actually navigating to the image link.

I guess, the explanation for this behavior is that images are handled by WebView internally, and thus they are not considered for downloading, see DownloadListener doesn't download images? But I agree that it's a bit odd that having the download attribute worked prior to KitKat.

But then the next problem you'll face when following the advice from Download Images using android webview is that DownloadManager doesn't work with data: URIs :) What you can do instead is just transform that base64-encoded image using Base64 utils into a binary blob, and save it yourself -- this way, you'll effectively get your image downloaded.

Upvotes: 4

Related Questions