如何获取文件的内容类型 [英] How to get the content-type of a file
问题描述
我正在实现一个处理GET
或HEAD
请求的HTTP/1.0服务器.
I am implementing a HTTP/1.0 server that processes GET
or HEAD
request.
我已经完成了Date
,Last-Modified
和Content-Length
,但是我不知道如何获取文件的Content-Type
.
I've finished Date
, Last-Modified
, and Content-Length
, but I don't know how to get the Content-Type
of a file.
它必须返回目录的目录(我可以使用stat()
函数完成),对于常规文件,对于text
或html
文件,返回text/html
,对于图像或
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.
是否应该使用文件名对其进行硬编码?
Should this be hard-coded, using the name of the file?
我想知道是否有任何功能可以获取此Content-Type
.
I wonder if there is any function to get this Content-Type
.
推荐答案
您可以查看文件扩展名(大多数Web服务器所做的就是-查看例如/etc/mime.types
文件;或者可以使用libmagic
通过查看文件的前几个字节来自动确定内容类型.
You could either look at the file extension (which is what most web servers do -- see e.g. the /etc/mime.types
file; or you could use libmagic
to automatically determine the content type by looking at the first few bytes of the file.
这篇关于如何获取文件的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!