我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
对于客户端计算机,可以通过以下方式实现:
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")
}
这是我的程序传输文件到一个特定的位置,并显示警报,如果它不存在
其他回答
我使用这个脚本添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
http://wap.w3schools.com/jsref/event_onerror.asp
您需要做的是向服务器发送一个请求,让它进行检查,然后将结果发回给您。
您试图与哪种类型的服务器通信?您可能需要编写一个小型服务来响应请求。
异步调用查看文件是否存在是更好的方法,因为它不会因为等待服务器的响应而降低用户体验。如果调用.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/
由于缓存,所有其他答案都可能失败!
向服务器上的文件发出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的主线程中检测到远程文件的存在-如图所示 在这里。
一种类似的和最新的方法。
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})