我如何检查我的服务器上的文件是否存在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/
其他回答
它为我工作,使用iframe忽略浏览器显示GET错误消息
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}
JavaScript函数检查文件是否存在:
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
return false;
} else {
console.log("File exists");
return true;
}
}
这对我来说很管用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
对于客户端计算机,可以通过以下方式实现:
try
{
var myObject, f;
myObject = new ActiveXObject("Scripting.FileSystemObject");
f = myObject.GetFile("C:\\img.txt");
f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
alert("file does not exist")
}
这是我的程序传输文件到一个特定的位置,并显示警报,如果它不存在
由于缓存,所有其他答案都可能失败!
向服务器上的文件发出HTTP请求可以被HTTP缓存拦截,然后返回缓存的响应。但是在此期间,该文件可能会在服务器上被删除,因此忽略缓存可能会返回假阳性结果。
合适的解决方案是创建非缓存的HTTP HEAD请求。Nik Sumeiko的回答使用了无缓存头,这意味着响应可以被缓存,但在重用之前必须重新验证。在这种情况下,服务器可能会返回304:Not Modified,而不是200:OK,因此是假阴性。
为了避免缓存,正确的头是cache - control: no-store
文件可以在没有HTTP 200响应的情况下存在
您还应该记住,可能会发生重定向(301:永久移动,307:临时重定向或308:永久重定向),因此文件可以存在于其他地方,并可能从不同的位置返回:根据用例,在这种情况下可以选择重定向而不是返回false。
另外请记住,如果您在不同的域上检查文件是否存在,并且它的CORS策略没有打开到您的服务器,后台请求将被阻止。在本例中,通常返回403:Forbidden,这并不意味着文件不存在,而是文件不可用。最后,同样适用于500:Internal Server Error响应,这意味着HTTP服务器未能处理请求,但该文件可以通过其他方式可用,例如通过FTP。
如果文件存在则返回true,如果不存在则返回false,如果文件不可用或重定向则返回undefined:
const fileExists = file =>
fetch(file, {method: 'HEAD', cache: 'no-store'})
.then(response => ({200: true, 404: false})[response.status])
.catch(exception => undefined);
fileExists("yourFile.html").then(yes => yes && alert("yourFile.html exists"));
// or in the async scope...
let yourFileExists = await fileExists("yourFile.html");
if(yourFileExists) console.log("It is there!")
else if(yourFileExists===false) console.log("Nope, it was deleted.");
else console.log("You are not worthy the answer, puny human!");
现代和过时的方法
既然我们现在生活在未来,我还会建议:
$.ajax()过时,不要在新项目中使用 XMLHttpRequest()过时,不要在新项目中使用 Fetch()现代方法,如果您可以自由选择,请使用它
注意GET/POST方法(如<img src…>)在这里不合适,因为它们通过下载文件浪费了网络流量(想象一下高分辨率照片和用户在连接较差的地区使用付费移动数据的最坏情况)
注意:现代PWA方法是使用缓存API和serviceWorker的fetch事件来拦截客户端和HTTP缓存之间的通信。在链接中的例子中,应该有这样的东西
if(event.request.cache=="no-store") {
// avoid cache storage and pass the request in the chain
// client - cache storage - HTTP cache - server
return fetch(event.request);
}
如果不这样做,缓存设置可能会被忽略,并且可能没有办法从运行serviceWorker的主线程中检测到远程文件的存在-如图所示 在这里。
推荐文章
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?