lua-resty-mime-sniff

嗅探给定数据的真实 MIME 类型

$ opm get spacewander/lua-resty-mime-sniff

名称

lua-resty-mime-sniff - 嗅探给定数据的真实 MIME 类型。

状态

[!Travis](https://travis-ci.org/spacewander/lua-resty-mime-sniff) [!覆盖率状态](https://coveralls.io/github/spacewander/lua-resty-mime-sniff?branch=master)

概要

    -- ¥ curl -F "file=@evil_script.jpg;type=image/jpeg"  localhost:8888
    -- You saied 'image/jpeg', but we found 'text/plain'
    local mime_sniff = require "lib.mime_sniff"
    local upload = require "resty.upload"
    
    local chunk_size = 1445 -- 512 is enough for the most cases
    
    local form, err = upload:new(chunk_size)
    if not form then
        ngx.log(ngx.ERR, "failed to new upload: ", err)
        ngx.exit(500)
    end
    
    form:set_timeout(1000)
    
    local submit_content_type
    local actual_content_type
    while true do
        local typ, res, err = form:read()
        if not typ then
            ngx.say("failed to read: ", err)
            return
        end
    
        if typ == "header" and res[1] == "Content-Type" then
            submit_content_type = res[2]
        elseif typ == "body" then
            --if not mime_sniff.match_content_type("image/jpeg") then
            --if not mime_sniff.match_content_type({"image/gif", "image/jpeg"}) then
            actual_content_type = mime_sniff.detect_content_type(res)
            break
        elseif typ == "eof" then
            break
        end
    end
    ngx.say("You saied '", submit_content_type, "', but we found '", actual_content_type, "'")

方法

detect_content_type

语法: content_type = mime_sniff.detect_content_type(data)

detect_content_type 可用于检测给定数据的真实 Content-Type。它最多考虑数据的前 1445 个字节,尽管对于大多数情况,前 512 个字节就足够了。此函数始终返回有效的 MIME 类型:如果无法确定更具体的类型,则返回 "application/octet-stream"。

match_content_type

语法: match_content_type = mime_sniff.match_content_type(data, types, ...)

match_content_type 检查给定数据的 Content-Type 是否与任何给定的类型匹配。types 是一个类数组表或字符串,并且数据长度应足够长。(最多 1445 字节,512 字节足够)请注意,types 的顺序很重要。第一个类型优先匹配。此函数将返回匹配的类型或 nil,如果给定的类型都不受支持,则抛出错误。有关支持的 MIME 类型的列表,请参阅 wiki:https://github.com/spacewander/lua-resty-mime-sniff/wiki/MIME-type-support-status

安装

您可以在您的项目中使用 lib/ 目录。

贡献

欢迎任何贡献!但是,在提交您的 pull request 之前,请阅读 指南

作者

spacewander

许可证

mit

版本