简体   繁体   English

如何获取文件的内容类型

[英]How to get the content-type of a file

I am implementing a HTTP/1.0 server that processes GET or HEAD request. 我正在实现一个处理GETHEAD请求的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. 我已经完成了DateLast-ModifiedContent-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()函数执行此操作),并返回常规文件的目录,对于texthtml文件,返回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.

相关问题 Symbian获取内容类型? - Symbian get content-type? 使用Wininet上传文件时如何添加正确的Content-Type? (HTTP PUT) - How to add correct Content-Type when uploading file with Wininet? (HTTP PUT) 如何设置.Net WebClient :: UploadString()的内容类型? - How to set content-type of .Net WebClient::UploadString()? 使用AWS c ++界面将文件上传到s3时Content-Type标记不正确 - Content-Type tag incorrect when uploading file to s3 using the AWS c++ interface nghttp2-asio:在标题中设置内容类型的正确方法 - nghttp2-asio : Proper way to set content-type in header Poco :: Net :: HTTPClientSession json数据未收到Content-Type - Poco::Net::HTTPClientSession json data Content-Type not received HTTP POST中缺少内容类型。 使用Webview进行QT - content-type missing in HTTP POST. QT using Webview libcurl HTTP 请求在 MIME 数据中设置 content-disposition 和 content-type - libcurl HTTP request set content-disposition and content-type in MIME data 如何在Linux上获取文件类型? - How to get file type on linux? 尽管正确设置了主机,方法和内容类型,但Poco库的PUT方法无法按预期工作 - Poco library PUT method not working as expected although host, method, content-type are set correctly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM