gpt4 book ai didi

php - 为什么我得到的 .csv 文件的 mime 类型为 "application/octet-stream"?

转载 作者:IT王子 更新时间:2023-10-29 00:54:55 27 4
gpt4 key购买 nike

我正在开发一个必须将 excel 文件导入 MySQL 的 PHP 应用程序。所以我需要将 excel 文件转换为 .csv 格式。但是当我想使用 $_FILE['something']['type'] 获取它的类型时,我得到 application/octet-stream 作为它的 mime 类型;< br/>我认为这里有问题。因为我将下面的列表收集为 .csv 文件 mime 类型:

text/comma-separated-values,  
text/csv,
application/csv,
application/excel,
application/vnd.ms-excel,
application/vnd.msexcel

怎么了?

最佳答案

在这种情况下,官方 HTTP 规范总是有帮助的。来自 RFC 2616 7.2.1 (我强调了):

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

问题的原因是接受文件上传的服务器本身并不知道上传的文件类型。为什么?因为它依赖于发送文件的 HTTP 消息来指定 Content-Type header 来确定确切的 mime-type。浏览器可能没有发送 Content-Type header ,并且服务器已根据上面的官方 HTTP 规范摘录采用 application/octet-stream。上传文件的客户端也可能选择不确定正在上传的文件的 MIME 类型,并发送了 Content-Type: application/octet-stream header 本身。

现在,当我们将其与 PHP manual entry regarding POST file uploadsdocs 结合考虑时,我们看到以下内容:

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

所以如你所见,即使指定了$_FILES['userfile']['type'],也只对应发送的Content-Type头由客户。此信息很容易被伪造,不应依赖。如果您需要确定上传的文件属于特定类型,则必须自行验证。

关于php - 为什么我得到的 .csv 文件的 mime 类型为 "application/octet-stream"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12061030/

27 4 0