简体   繁体   中英

How to get extension of image from URL?

I'm working on a react native application which fetches image from URL and saves in local device.

const getExtention = (filename) => {
  return /[.]/.exec(filename) ? /[^.]+$/.exec(filename) : undefined;
};

I'm using the above code for getting image extension for this kind of files. https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg

But there are also some image urls available without extension like below

https://media.gettyimages.com/photos/woman-lifts-her-arms-in-victory-mount-everest-national-park-picture-id507910624?s=612x612

so how can i know what extension theabove image is ? to store in device

As someone have already suggested in comments about MIME type mapping and in agreement I would say, to detect/fetch extension of remote file URLs, you can't do it without knowing it's MIME type.

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();

With above code, I was able to get its type, which is image/jpeg . Now, to convert MIME type to .ext, you can either create your own list to do that or use any of below packages:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM