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.
Asked
Active
Viewed 1.9k times
10
-
1http://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript Given here – I-Kod Sep 12 '15 at 15:16
-
Related here: http://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript – Gaston Ambrogi May 23 '16 at 23:52
-
Why would XSS be a problem? Simply use the DOM methods to set the src of the HTMLImageElement displaying that image instead of using innerHTML. – Kaiido Apr 01 '21 at 08:09
2 Answers
3
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)
}
}))
}

JimmyTheCode
- 3,783
- 7
- 29
- 71

Mohamad Khani
- 332
- 4
- 13
2
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.

wolfshirts
- 43
- 5
-
This won't work. You have to return a promise for it to work (how can you return false on an callback event ?! – Bruno Marotta Feb 12 '21 at 07:25