检测加载的图像是否为不带文件扩展名的SVG

时间:2018-08-16 23:32:52

标签: javascript html

我需要知道图像文件是SVG(用于备用)的位置,但是我正在使用的CMS不会放弃URL中的文件扩展名。

如何仍然知道加载的图像是否为SVG?

(URL看起来像这样的domain.com/files/images/100,其中100是图片的ID。)

2 个答案:

答案 0 :(得分:2)

您可以发送一个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();

答案 1 :(得分:1)

URL仍然不能确定文件类型,example.com / foo.jpg可能是SVG。决定文件类型的是content-type HTTP标头,我们可以通过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'),
);
相关问题