use*_*est 255 javascript file-io jquery
如何检查我的服务器上的文件是否存在于jQuery或纯JavaScript中?
cic*_*chy 426
使用jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:
这是用于检查404状态的代码,而不使用jQuery
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Run Code Online (Sandbox Code Playgroud)
小的更改,它可以检查状态HTTP状态代码200(成功),而不是.
Mat*_*vis 70
一种类似且更新的方法.
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
Run Code Online (Sandbox Code Playgroud)
小智 66
这对我有用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
Run Code Online (Sandbox Code Playgroud)
Gin*_*ino 44
我用这个脚本添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<img src="image.gif" onerror="imgError()" />
Run Code Online (Sandbox Code Playgroud)
http://wap.w3schools.com/jsref/event_onerror.asp
Moo*_*oob 22
只要您在同一个域上测试文件,这应该有效:
function fileExists(url) {
if(url){
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
return req.status==200;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,此示例使用GET请求,除了获取标题(您需要检查天气文件存在所需)之外,还会获取整个文件.如果文件足够大,则此方法可能需要一段时间才能完成.
更好的方法是更改此行:req.open('GET', url, false);toreq.open('HEAD', url, false);
Sha*_*aun 16
在尝试运行此问题的答案时,我收到了跨域权限问题,所以我选择了:
function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
return true;
}).bind('error', function() {
return false;
});
}
Run Code Online (Sandbox Code Playgroud)
它似乎工作得很好,希望这有助于某人!
Jan*_*roň 15
可以使用 HTTP 缓存拦截对服务器上的文件发出的 HTTP 请求,然后返回缓存的响应。但同时该文件可能会在服务器上被删除,因此忽略缓存可能会返回误报结果。
正确的解决方案是创建非缓存的 HTTP HEAD 请求。Nik Sumeiko 的答案使用标头,这意味着可以缓存no-cache响应,但在重用之前必须重新验证。在这种情况下,服务器可能会返回,但实际上不是,因此会出现漏报。304: Not Modified200: OK
为了避免缓存,正确的标头是Cache-Control: no-store
您还应该记住,可能会发生重定向(301: Moved Permanently、307: Temporary Redirect或308: Permanent Redirect),因此文件可以存在于其他地方,并且可能从不同位置返回:根据用例,在这种情况下可以选择遵循重定向而不是返回 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!");
Run Code Online (Sandbox Code Playgroud)
由于我们现在生活在未来,我还建议:
注意GET/POST 方法(如<img src...>)在这里不合适,因为它们通过下载文件浪费网络流量(想象一下最糟糕的情况,高分辨率照片和用户在连接较差的区域使用付费移动数据)
注意现代 PWA 方法是将 Cache 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);
}
Run Code Online (Sandbox Code Playgroud)
如果没有这个,缓存设置可能会被忽略,并且可能无法在 serviceWorker 运行的情况下从主线程检测远程文件的存在 - 此处所示。
如果您使用的是Babel Transpiler或Typescript 2,以下是ES7的操作方法:
async function isUrlFound(url) {
try {
const response = await fetch(url, {
method: 'HEAD',
cache: 'no-cache'
});
return response.status === 200;
} catch(error) {
// console.log(error);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在其他async作用域内,您可以轻松地检查url是否存在:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我使用这个脚本来检查文件是否存在(它还处理跨源问题):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
Run Code Online (Sandbox Code Playgroud)
请注意,当被检查的文件不包含 JSON 时,将引发以下语法错误。
未捕获的语法错误:意外的标记 <
| 归档时间: |
|
| 查看次数: |
408961 次 |
| 最近记录: |