[英]How to get the content-type of a file
I am implementing a HTTP/1.0 server that processes GET
or HEAD
request. 我正在实现一个处理
GET
或HEAD
请求的HTTP / 1.0服务器。
I've finished Date
, Last-Modified
, and Content-Length
, but I don't know how to get the Content-Type
of a file. 我已经完成了
Date
, Last-Modified
和Content-Length
,但是我不知道如何获取文件的Content-Type
。
It has to return directory for directory(which I can do using stat()
function), and for a regular file, text/html
for text
or html
file, and image/gif
for image or gif
file. 它必须返回目录的目录(我可以使用
stat()
函数执行此操作),并返回常规文件的目录,对于text
或html
文件,返回text/html
,对于图像或gif
文件,返回image/gif
。
Should this be hard-coded, using the name of the file? 是否应该使用文件名对其进行硬编码?
I wonder if there is any function to get this Content-Type
. 我想知道是否有任何函数来获取此
Content-Type
。
您可以查看文件扩展名(大多数Web服务器都执行此操作-参见例如/etc/mime.types
文件;也可以使用libmagic
通过查看文件的前几个字节来自动确定内容类型。 。
It depends how sophisticated you want to be. 这取决于您想要变得多么复杂。
If the files in question are all properly named and there are only several types to handle, having a switch based file suffix is sufficient. 如果有问题的文件都被正确命名,并且只有几种类型可以处理,那么具有基于开关的文件后缀就足够了。 Going to the extreme case, making the right decision no matter what the file is would probably require either duplicating the functionality of Unix
file
command or running it on file in question (and then translating the output to the proper Content-Type
). 在极端情况下,无论文件是什么,做出正确的决定都可能需要复制Unix
file
命令的功能或在有问题的文件上运行它(然后将输出转换为适当的Content-Type
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.