简体   繁体   中英

Check html file exist on server using javascript

My ASPX code generated some html files where I just put link for paging like

<a href="1.html">First</a>&nbsp;|&nbsp;
<a href="3.html">Next</a>&nbsp;|&nbsp;
<a href="1.html">Previous</a>&nbsp;|&nbsp;
<a href="9.html">Last</a>

say if user currently on second page when it press Next moves to 3rd page ...

now issue is when user clicking Next button several times and system is in progress to generate let say 5th page it will show error page.

Is there any way to check from html via javascript to check whether file is present or not? Kindly help me to pull out from this show stopper issue

You can use ajax for check file exists or not

Using Jquery

$.ajax({
        url:'http://www.example.com/3.html',
        error: function()
        {
           alert('file does not exists');
        },
        success: function()
        {
            alert('file exists');
        }
    });

Using Javascript

function checkIfRemoteFileExists(fileToCheck)
{
    var tmp=new Image;
    tmp.src=fileToCheck;

    if(tmp.complete)        
        alert(fileToCheck+" is available");        
    else        
     alert(fileToCheck+" is not available");        
}

Now to check if file exists or not call js function like this

checkIfRemoteFileExists('http://www.yoursite.com/abc.html');​
  • There is an issue with @Sibu's solution: it actually downloads the file (it can be potentionally big, wasting traffic)
  • In the 2021, one should not use jQuery in new projects
  • native Promises and Fetch are the way to go today
<output id="output"></output>

<script>
// create a non-cached HTTP HEAD request
const fileExists = file =>
  fetch(file, {method: 'HEAD', cache: 'no-store'})
  .then(r => r.status==200);

// check the file existence on the server
// and place the link asynchronously after the response is given
const placeNext = file => fileExists(file).then(yes => output.innerHTML = 
   (yes ? `<a href="3.html">Next</a>` : '')
);

// place the "next" link in the output if "3.html" exists on the server
placeNext('3.html');
</script>

i like to use this type of script

function CheckFileExist(fileToCheck: string) {

    return new Promise((resolve, reject) => {
        fetch(fileToCheck).then(res => {
            if (res.status == 404) resolve(false);
            if (res.status == 200) resolve(true);
            return res.text()
        }) 
    })

}

and use it

 var exists = await CheckFileExist(link);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM