11

Is there an easy way to check if a base64 image url is valid? I'm getting the base64 url from server via ajax/xhr and want to avoid xss on my site.

3

2 Answers 2

4

I wrote an async function using @wolfshirts answer. It worked for me.

@wolfshirts function will not work because the return line was placed in the wrong scope.

async function isBase64UrlImage(base64String: string) {
  let image = new Image()
  image.src = base64String
  return await (new Promise((resolve)=>{
    image.onload = function () {
      if (image.height === 0 || image.width === 0) {
        resolve(false);
        return;
      }
      resolve(true)
    }
    image.onerror = () =>{
      resolve(false)
    }
  }))
}
Sign up to request clarification or add additional context in comments.

Comments

3

I'm not sure if you're trying to validate the image itself, or the URL. Validating the image can be tricky. I would first run a check against known base64 MIME types.

'/' means jpeg.

'i' means png.

'R' means gif.

'U' means webp.

let data = //suspectedBase64Image
    
    
function isImage(data){
    let knownTypes = {
      '/': 'data:image/jpg;base64,',
      'i': 'data:image/png;base64,',
      /*ETC*/
      }
      
      let image = new Image()
      
      if(!knownTypes[data[0]]){
        console.log("encoded image didn't match known types");
        return false;
      }else{
        image.src = knownTypes[0]+data
        image.onload = function(){
          //This should load the image so that you can actually check
          //height and width.
          if(image.height === 0 || image.width === 0){
            console.log('encoded image missing width or height');
            return false;
          }
      }
      return true;
}

This is some basic sanity checking you could use.

You could go deeper and convert magic numbers to base64 then check for them within the base64 data. This code makes the assumption that you're missing the data type at the start. Some base64 will have the data type shown in the dictionary at the start of the base64.

1 Comment

This won't work. You have to return a promise for it to work (how can you return false on an callback event ?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.