我需要知道图像文件在哪里是 SVG(用于后备),但我使用的 CMS 不会泄露 URL 中的文件扩展名。
我如何才能知道加载的图像是否为 SVG?
(URL 看起来像这样domain.com/files/images/100,其中 100 是图像的 id。)
我需要知道图像文件在哪里是 SVG(用于后备),但我使用的 CMS 不会泄露 URL 中的文件扩展名。
我如何才能知道加载的图像是否为 SVG?
(URL 看起来像这样domain.com/files/images/100,其中 100 是图像的 id。)
URL 无论如何都不能确定文件类型,example.com/foo.jpg 可能是 SVG。决定文件类型的是content-typeHTTP 标头,我们可以通过 HEAD 请求有效地获取它,该请求获取标头而不是图像本身。
async function urlIsSvg(url) {
const r = await fetch(url, {method: 'HEAD'});
return r.headers.get('content-type') === 'image/svg+xml';
}
console.log(
await urlIsSvg('https://picsum.photos/100'),
await urlIsSvg('https://upload.wikimedia.org/wikipedia/commons/3/30/Vector-based_example.svg'),
);
您可能会发送一个HEAD请求并获得一个content-type标头:
var src = 'https://picsum.photos/100';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.getResponseHeader('content-type'))
}
};
xhttp.open("HEAD", src, true);
xhttp.send();