我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
异步调用查看文件是否存在是更好的方法,因为它不会因为等待服务器的响应而降低用户体验。如果调用.open,将第三个参数设置为false(如上面的许多示例,例如http. open)。open('HEAD', url, false);),这是一个同步调用,您会在浏览器控制台中得到一个警告。
更好的方法是:
function fetchStatus( address ) {
var client = new XMLHttpRequest();
client.onload = function() {
// in case of network errors this might not give reliable results
returnStatus( this.status );
}
client.open( "HEAD", address, true );
client.send();
}
function returnStatus( status ) {
if ( status === 200 ) {
console.log( 'file exists!' );
}
else {
console.log( 'file does not exist! status: ' + status );
}
}
来源:https://xhr.spec.whatwg.org/
其他回答
这对我来说很管用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
这是对公认答案的改编,但我不能从答案中得到我需要的东西,必须测试它是否有效,因为这是一种直觉,所以我把我的解放在这里。
我们需要验证一个本地文件是否存在,并且只允许该文件(PDF)在存在的情况下打开。如果你省略了网站的URL,浏览器将自动确定主机名-使其在localhost和服务器上工作:
$.ajax({
url: 'YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf',
type: 'HEAD',
error: function () {
//file not exists
alert('PDF does not exist');
},
success: function () {
//file exists
window.open('YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf', "_blank", "fullscreen=yes");
}
});
我想要一个函数,将返回布尔值,我遇到了闭包和异步性相关的问题。我是这样解决的:
checkFileExistence= function (file){
result=false;
jQuery.ajaxSetup({async:false});
$.get(file)
.done(function() {
result=true;
})
.fail(function() {
result=false;
})
jQuery.ajaxSetup({async:true});
return(result);
},
您需要做的是向服务器发送一个请求,让它进行检查,然后将结果发回给您。
您试图与哪种类型的服务器通信?您可能需要编写一个小型服务来响应请求。
这并没有解决OP的问题,但对于任何从数据库返回结果的人来说:这里是我使用的一个简单方法。
如果用户没有上传头像,头像字段将为NULL,所以我将从img目录插入一个默认头像图像。
function getAvatar(avatar) {
if(avatar == null) {
return '/img/avatar.jpg';
} else {
return '/avi/' + avatar;
}
}
then
<img src="' + getAvatar(data.user.avatar) + '" alt="">