如何安全地从URL获取文件扩展名? [英] How to safely get the file extension from a URL?
问题描述
考虑以下网址
http://m3u.com/tunein.m3u
http://asxsomeurl.com/listen.asx:8024
http://www.plssomeotherurl.com/station.pls?id=111
http://22.198.133.16:8024
确定文件扩展名(.m3u/.asx/.pls)的正确方法是什么?显然最后一个没有文件扩展名.
Whats the proper way to determine the file extensions (.m3u/.asx/.pls)? Obviously the last one doesn't have a file extension.
我忘了提到m3u/asx/pls是音频流的播放列表(文本文件),必须以不同的方式进行解析.目标确定扩展名,然后将URL发送到适当的解析功能.例如.
I forgot to mention that m3u/asx/pls are playlists (textfiles) for audio streams and must be parsed differently. The goal determine the extension and then send the url to the proper parsing-function. E.g.
url = argv[1]
ext = GetExtension(url)
if ext == "pls":
realurl = ParsePLS(url)
elif ext == "asx":
realurl = ParseASX(url)
(etc.)
else:
realurl = url
Play(realurl)
GetExtension()应该返回文件扩展名(如果有),最好不要连接到URL.
GetExtension() should return the file extension (if any), preferrably without connecting to the URL.
推荐答案
real 正确的方法是根本不使用文件扩展名.对相关网址执行GET(或HEAD)请求,然后使用返回的"Content-type" HTTP标头获取内容类型.文件扩展名不可靠.
The real proper way is to not use file extensions at all. Do a GET (or HEAD) request to the URL in question, and use the returned "Content-type" HTTP header to get the content type. File extensions are unreliable.
请参见 MIME类型(IANA媒体类型)有关更多信息和有用的MIME类型的列表.
See MIME types (IANA media types) for more information and a list of useful MIME types.
这篇关于如何安全地从URL获取文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!