简体   繁体   English

如何从URL获取文件扩展名

[英]how to get file extension from url

I am trying to create a js file downloader module. 我正在尝试创建一个js文件下载器模块。 Right now I stumbled on some file urls like - https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTA_Rg2GwJVJEmOGGoYFev_eTSZAjkp_stpi4cUXpjWbE6Wh7gSpCvldg . 现在,我偶然发现了一些文件URL,例如-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 ? 我的问题是如何只知道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 如@melpomene所建议,您可以对文件进行HEAD请求,从响应头获取Content-Type

 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, "")}`)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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