Upload an image if it is found, otherwise upload another image

what i need to do is just say, but (for me) it’s hard to do:

using javascript , given the name of the image, that is, "image01.jpg", I need to check if this image exists in a specific folder or path (local or on the Internet). If the image does not exist in this folder, I need to check if the same image exists in another folder.

e.g. with pseudo code

imageToFind = 'image01.jpg' path1 = 'users/john/images' path2 = 'users/mike/img' if path1+'/'+imageToFind exists //do something else if path2+'/'+imageToFind exists //do something else print('NOT FOUND') 

What approach do you suggest? I tried to achieve this using ajax first and then using javascript Image (), but I was not able to complete both of these cases.

Thanks in advance for any help, best regards

+6
source share
4 answers

You can rely heavily on your own onload and onerror onload onerror , which fire for Image nodes. So it might look like

 var images = ['users/john/images/image01.jpg','users/mike/img/image01.jpg','some/more/path/image01.jpg']; (function _load( img ) { var loadImage = new Image(); loadImage.onerror = function() { // image could not get loaded, try next one in list _load( images.shift() ); }; loadImage.onload = function() { // this image was loaded successfully, do something with it }; loadImage.src = img; }( images.shift() )); 

This code probably does a little more than you really requested. You can basically, but as many image paths as you want in this array, the script will search the list until it can load a single image.

+3
source

Use onerror callback:

 var img = new Image(); img.onerror = function(){ img = new Image(); // clean the error (depends on the browser) img.onerror = function(){ console.log('not found at all !'); }; img.src = path2+'/'+imageToFind; }; img.src = path1+'/'+imageToFind; 
+6
source

try something like

 objImg = new Image(); objImg.src = 'photo.gif'; if(!objImg.complete) { img.src = path2+'/'+imageToFind; //load other image }else{ img.src = path1+'/'+imageToFind; } 
+1
source

I think you need to ask yourself: why I do not know if images exist?

I feel that you should not have this problem or you want to solve it this way.

0
source

All Articles