使用 JavaScript 检查服务器上是否存在图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18837735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if image exists on server using JavaScript?
提问by 0xhughes
Using javascript is there a way to tell if a resource is available on the server? For instance I have images 1.jpg - 5.jpg loaded into the html page. I'd like to call a JavaScript function every minute or so that would roughly do the following scratch code...
使用 javascript 有没有办法判断服务器上的资源是否可用?例如,我将图像 1.jpg - 5.jpg 加载到 html 页面中。我想每分钟左右调用一次 JavaScript 函数,大致执行以下临时代码...
if "../imgs/6.jpg" exists:
var nImg = document.createElement("img6");
nImg.src = "../imgs/6.jpg";
Thoughts? Thanks!
想法?谢谢!
回答by ajtrichards
You could use something like:
你可以使用类似的东西:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
Obviously you could use jQuery/similar to perform your HTTP request.
显然,您可以使用 jQuery/similar 来执行您的 HTTP 请求。
$.get(image_url)
.done(function() {
// Do something now you know the image exists.
}).fail(function() {
// Image doesn't exist - do something else.
})
回答by epascarello
You can use the basic way image preloaders work to test if an image exists.
您可以使用图像预加载器的基本工作方式来测试图像是否存在。
function checkImage(imageSrc, good, bad) {
var img = new Image();
img.onload = good;
img.onerror = bad;
img.src = imageSrc;
}
checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );
回答by adeneo
You can just check if the image loads or not by using the built in events that is provided for all images.
您可以使用为所有图像提供的内置事件来检查图像是否加载。
The onload
and onerror
events will tell you if the image loaded successfully or if an error occured :
在onload
与onerror
事件将告诉你,如果图像成功加载或发生错误后:
var image = new Image();
image.onload = function() {
// image exists and is loaded
document.body.appendChild(image);
}
image.onerror = function() {
// image did not load
var err = new Image();
err.src = '/error.png';
document.body.appendChild(err);
}
image.src = "../imgs/6.jpg";
回答by Jordan Bonitatis
If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here
如果有人来到此页面希望在基于React的客户端中执行此操作,您可以执行以下操作,这是 React 团队的 Sophia Alpert 在此处提供的原始答案
getInitialState: function(event) {
return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
return (
<img onError={this.handleError} src={src} />;
);
}
回答by Douglas
If you create an image tag and add it to the DOM, either its onload or onerror event should fire. If onerror fires, the image doesn't exist on the server.
如果您创建一个图像标记并将其添加到 DOM,则应触发其 onload 或 onerror 事件。如果 onerror 触发,则该图像在服务器上不存在。
回答by attacomsian
A better and modern approach is to use ES6 Fetch APIto check if an image exists or not:
一种更好的现代方法是使用 ES6 Fetch API来检查图像是否存在:
fetch('https://via.placeholder.com/150', { method: 'HEAD' })
.then(res => {
if (res.ok) {
console.log('Image exists.');
} else {
console.log('Image does not exist.');
}
}).catch(err => console.log('Error:', err));
Make sure you are either making the same-origin requests or CORS is enabled on the server.
确保您正在发出同源请求或在服务器上启用 CORS。
回答by HynekS
Basicaly a promisifiedversion of @espascarello and @adeneo answers, with a fallback parameter:
基本上是@espascarello和@adeneo 答案的promisified版本,带有后备参数:
const getImageOrFallback = (path, fallback) => {
return new Promise(resolve => {
const img = new Image();
img.src = path;
img.onload = () => resolve(path);
img.onerror = () => resolve(fallback);
});
};
// Usage:
const link = getImageOrFallback(
'https://www.fillmurray.com/640/360',
'https://via.placeholder.com/150'
).then(result => console.log(result) || result)
// It can be also implemented using the async / await API.
Note:I may personally like the fetch
solution more, but it has a drawback – if your server is configured in a specific way, it can return 200 / 304, even if your file doesn't exist. This, on the other hand, will do the job.
注意:我个人可能fetch
更喜欢该解决方案,但它有一个缺点——如果您的服务器以特定方式配置,即使您的文件不存在,它也可能返回 200 / 304。另一方面,这将完成工作。
回答by Ani Menon
You may call this JS function to check if file exists on the Server:
您可以调用这个 JS 函数来检查服务器上是否存在文件:
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;
}
}
回答by Rohith Murali
You can do this with your axios by setting relative path to the corresponding images folder. I have done this for getting a json file. You can try the same method for an image file, you may refer these examples
您可以通过设置相应图像文件夹的相对路径来使用 axios 执行此操作。我这样做是为了获取一个 json 文件。您可以对图像文件尝试相同的方法,您可以参考这些示例
If you have already set an axios instance with baseurl as a server in different domain, you will have to use the full path of the static file server where you deploy the web application.
如果您已经使用 baseurl 将 axios 实例设置为不同域中的服务器,则必须使用部署 Web 应用程序的静态文件服务器的完整路径。
axios.get('http://localhost:3000/assets/samplepic.png').then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})
If the image is found the response will be 200 and if not, it will be 404.
如果找到图像,则响应为 200,否则为 404。
Also, if the image file is present in assets folder inside src, you can do a require, get the path and do the above call with that path.
此外,如果图像文件存在于 src 内的资产文件夹中,您可以执行要求,获取路径并使用该路径执行上述调用。
var SampleImagePath = require('./assets/samplepic.png');
axios.get(SampleImagePath).then(...)
回答by MAtkins
This works fine:
这工作正常:
function checkImage(imageSrc) {
var img = new Image();
try {
img.src = imageSrc;
return true;
} catch(err) {
return false;
}
}