Reputation: 267
We have image in D:\img\need.png. We need to know image exist or not.We tried like this:-- It's call error method always
$.ajax({
url:'http://www.himansuit.com//modiyojana.jpg',
type:'HEAD',
error: function(jqXHR, textStatus, errorThrown)
{
alert("file does not exist");
console.log(textStatus);
console.log(jqXHR);
console.log(errorThrown);
},
success: function()
{
alert("file exists do something here");//file exists do something here
}
});
Please guide me .What wrong in my code .How check file exist or not in my system using ajax call
We got Error this
Upvotes: 1
Views: 1281
Reputation: 3919
As told in comments, you first have to set up a web server on your local OS. For example Apache, or even a node web server. Installation depends on your system.
Then, you have to write a script which receives a file path and check if there is a file here.
So, your ajax call will looks like that:
$.ajax({
url: 'http://localhost/script_path/script.php' //or script.js, or...
+'?path=D:/img/need.png',
type:'GET',
error: function(jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
console.log(jqXHR);
console.log(errorThrown);
},
success: function( response )
{
if( response )
alert("file exists do something here");//file exists do something here
else
alert("file does not exist");
}
});
edit
To check if a file exists, hosted on a different domain, without having a CORS restriction:
function checkFileExists( url ){
var img= document.createElement('img');
img.style.display= "none";
img.onload= function(){ alert( url + " exists")};
img.onerror= function(){ alert( url + " does not exists")};
img.src= url;
}
checkFileExists("http://www.himansuit.com/modiyojana.jpg");
checkFileExists("http://www.fakedomain.com/modiyojana.jpg");
Upvotes: 0
Reputation: 146
In server side use script like this.
<?php $filename = '/path/to/foo.txt'; if (file_exists($filename)) {echo "1";//existed
}else { echo "0";//not}?>
In front end script do ,
$.ajax({
url:'checkfileexists.php',
type:'post',
error: function(jqXHR, textStatus, errorThrown)
{
alert("file does not exist");
console.log(textStatus);
console.log(jqXHR);
console.log(errorThrown);
},
success: function(data)
{
if(data==1)
alert("file exists do something here");//file exists do something
else
alert("not");
}
});
Upvotes: 1