简体   繁体   中英

how to get file extension from url

I am trying to create a js file downloader module. Right now I stumbled on some file urls like - https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTA_Rg2GwJVJEmOGGoYFev_eTSZAjkp_stpi4cUXpjWbE6Wh7gSpCvldg .

My question here is how to get the proper extension of the file knowing only the url ?

The only idea I have is to use this module to check the file after I download it.

As suggested by @melpomene you can make HEAD request for file, get Content-Type from response headers

 fetch("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTA_Rg2GwJVJEmOGGoYFev_eTSZAjkp_stpi4cUXpjWbE6Wh7gSpCvldg", {method:"HEAD"}) .then(response => response.headers.get("Content-Type")) .then(type => console.log(`.${type.replace(/.+\\/|;.+/g, "")}`)); 

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