我正在开发一个 React Native 应用程序,它从 URL 获取图像并保存在本地设备中。
const getExtention = (filename) => {
return /[.]/.exec(filename) ? /[^.]+$/.exec(filename) : undefined;
};
我正在使用上面的代码来获取此类文件的图像扩展名。 https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg
但也有一些不带扩展名的图像网址,如下所示
https://media.gettyimages.com/photos/woman-lifts-her-arms-in-victory-mount-everest-national-park-picture-id507910624?s=612x612
那么我怎么知道上面的图片的扩展名是什么?存储在设备中
最佳答案
正如有人在有关 MIME 类型映射的评论中建议的那样,并且我同意,要检测/获取远程文件 URL 的扩展名,如果不知道它的 MIME 类型,您就无法做到这一点。
var url = 'https://media.gettyimages.com/photos/woman-lifts-her-arms-in-victory-mount-everest-national-park-picture-id507910624?s=612x612';
var xhttp = new XMLHttpRequest();
xhttp.open('HEAD', url);
xhttp.onreadystatechange = function () {
if (this.readyState == this.DONE) {
console.log(this.getResponseHeader("Content-Type"));
}
};
xhttp.send();
通过上面的代码,我能够获取它的类型,即image/jpeg。现在,要将 MIME 类型转换为 .ext,您可以创建自己的列表来执行此操作,也可以使用以下任何包:
关于javascript - 如何从URL中获取图像的扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64423695/