[英]How to check the availability of a resource using JavaScript?
If I have a URL to a video file, how can I detect if the resource pointed by the URL is valid and exists before it can be displayed? 如果我有一个视频文件的URL,那么如何显示该URL指向的资源是否有效并存在,然后才能显示该资源? I've seen some answers suggesting AJAX, but I only know AJAX to send and retrieve some data, not to get the status of the file whether it exists or not. 我已经看到一些建议使用AJAX的答案,但是我只知道AJAX发送和检索一些数据,而不是获取文件状态(无论是否存在)。
For example, if I have a URL like http://www.example.com/video.mp4
, how could I check whether video.mp4
exists or not and can or cannot be retrieved? 例如,如果我有一个类似http://www.example.com/video.mp4
的URL,该如何检查video.mp4
是否存在以及是否可以检索?
You don't really need ajax, just create a video element, and see if it can load the source 您实际上并不需要ajax,只需创建一个video元素,然后查看它是否可以加载源
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';
Different browsers play different formats, to check if the file can be played in the current browser, you can use the canplaythrough
event 不同的浏览器播放不同的格式,要检查文件是否可以在当前浏览器中播放,可以使用canplaythrough
事件
video.oncanplaythrough = function() {
alert("This file can be played in the current browser");
};
if the file is on the same domain, and ports and protocol match, you can use ajax to do a HEAD request and see if the resource exists, but that won't work cross-domain 如果文件在同一个域上,并且端口和协议匹配,则可以使用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();
You can send a HEAD
request. 您可以发送HEAD
请求。 HEAD
requests send back only the HTTP headers, so if you get a status of 200 or 304 it means the resource exists, if you get a 404 it means the resource doesn't exist. HEAD
请求仅发回HTTP标头,因此,如果状态为200或304,则表示资源存在;如果状态为404,则表示资源不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.