How to check resource availability using JavaScript?

If I have a video file URL, how can I determine if the resource specified by the URL really exists and exists before it is displayed? I saw some answers suggesting AJAX, but I only know AJAX for sending and receiving some data, and not for getting the status of a file, whether it exists or not.

For example, if I have a URL, for example http://www.example.com/video.mp4, how can I check if it exists or not video.mp4and can or cannot be obtained?

+4
source share
2 answers

You don't need ajax, just create a video element and see if it can load the source

var video = document.createElement('video');

video.onload = function() {
    alert('success, it exsist');
    // show video element
}

video.onerror = function() {
    alert('error, couldn\'t load');
    // don't show video element
}

video.src = 'http://www.example.com/video.mp4';

, , , canplaythrough

video.oncanplaythrough = function() {
    alert("This file can be played in the current browser");
};

, , ajax HEAD , ,

var http = new XMLHttpRequest();
http.open('HEAD', '/folder/video.mp4');

http.onreadystatechange = function() {
    if (this.readyState == this.DONE) {
        if (this.status != 404) {
          // resource exists
        }
    }
};

http.send();
+6

HEAD. HEAD HTTP-, , 200 304, , , 404, , .

0

All Articles