How to check whether a string is base64 encoded or not?

Aziz Sirojiddinov :

I want to check HTML img src is in base64 encoded format or not in my java spring backend. if it is Base64 encoded then I will just decode image and save to my server if it is not I will download firstly based on image URL path then save to my server. I've built a downloading image and decoding image functions. But can't resolve the base64 check. I tried to use try catch checking statement but I do not need catching error if it is not base64. P.S I am using java.util.Base64

public boolean isBase64(String path) {
   try {
        Base64.getDecoder().decode(path);

    } catch(IllegalArgumentException e) {   
    }
}
edwgiz :

If you receive the exact value by <img src="..." /> attribute then it should have Data URL format

The simple regexp could determine whether the URL is Data or regular. In java it can look like

    private static final Pattern DATA_URL_PATTERN = Pattern.compile("^data:image/(.+?);base64,\\s*", Pattern.CASE_INSENSITIVE);

    static void handleImgSrc(String path) {
        if (path.startsWith("data:")) {
            final Matcher m = DATA_URL_PATTERN.matcher(path);
            if (m.find()) {
                String imageType = m.group(1);
                String base64 = path.substring(m.end());
                // decodeImage(imageType, base64);
            } else {
                // some logging
            }
        } else {
            // downloadImage(path);
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358356&siteId=1