萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx + ngx_lua (OpenResty) 獲取 GET/POST 參數完整指南:含 multipart/form-data 處理

基礎版:標準 application/x-www-form-urlencoded

local request_method = ngx.var.request_method
local args = nil

if request_method == "GET" then
    args = ngx.req.get_uri_args()
elseif request_method == "POST" then
    ngx.req.read_body()                    -- 必須先讀取 body
    args = ngx.req.get_post_args()         -- 解析 application/x-www-form-urlencoded
end

local param  = args["param"]
local param2 = args["param2"]

-- 多值參數 (如 checkbox) 返回 table
local ids = args["ids"]  -- {"1","2","3"} 或 "1" (單值)
if type(ids) == "table" then
    -- 處理陣列
end

注意: get_post_args() 僅解析 application/x-www-form-urlencoded 與 multipart/form-data (僅非檔案欄位),**不支援檔案上傳欄位提取**。

進階版:完整解析 multipart/form-data (含檔案上傳)

原文提供的 Lua 代碼手動解析 multipart body,但在 OpenResty 生產環境**強烈建議使用成熟庫**:

推薦:lua-resty-upload (OpenResty 官方生態)

local upload = require "resty.upload"
local chunk_size = 4096
local form = upload:new(chunk_size)
form:set_timeout(1000)  -- 1 秒超時

local args = {}
local file_args = {}

while true do
    local typ, res, err = form:read()
    if not typ then
        ngx.log(ngx.ERR, "upload read error: ", err)
        return ngx.exit(500)
    end

    if typ == "header" then
        -- res = {"Content-Disposition", "form-data; name=\"field1\"; filename=\"a.txt\""}
        local key = res[1]
        local value = res[2]
        local name = value:match('name="([^"]+)"')
        local filename = value:match('filename="([^"]+)"')
        if filename then
            -- 檔案欄位
            file_args[name] = { filename = filename, content_type = headers["Content-Type"] }
            -- 這裡可將檔案流儲存至磁碟/上游
        else
            -- 普通欄位,準備接收 body
            args[name] = ""
        end
    elseif typ == "body" then
        -- 累加 body 內容
        if file_args[current_name] then
            -- 寫入檔案或暫存
        else
            args[current_name] = (args[current_name] or "") .. res
        end
    elseif typ == "part_end" then
        -- 單個 part 結束
    elseif typ == "eof" then
        break  -- 全部讀取完成
    end
end

-- args 現在包含所有非檔案欄位
-- file_args 包含檔案元資訊

替代:lua-resty-multipart-parser (輕量解析器)

local multipart = require "multipart"
local parser = multipart(ngx.var.http_content_type, chunk_size)
parser:set_handler({
    on_field = function(name, value)
        args[name] = value
    end,
    on_file_begin = function(name, filename, content_type)
        file_args[name] = { filename = filename, content_type = content_type }
    end,
    on_file_data = function(name, data)
        -- 寫入檔案
    end,
})
parser:parse(ngx.req.get_body_data())

關鍵陷阱與最佳實踐

陷阱說明對策
未調用 read_body()POST 請求 body 未讀入記憶體/臨時檔,get_post_args() 返回空表POST 處理開頭**必須** ngx.req.read_body()
body 大於 client_body_buffer_size超過緩衝區 (預設 8k/16k) 會寫入臨時檔,get_body_data() 返回 nil用 ngx.req.get_body_file() 讀取臨時檔,或增大 client_body_buffer_size
手動解析 multipart 邊界錯誤邊界字串包含在 body 中、換行符處理 (CRLF vs LF)、巢狀 multipart**使用成熟庫**,勿手寫解析器
參數名重複 (陣列)ids=1&ids=2 或 ids[]=1&ids[]=2Lua 返回 table,統一按 table 處理
URL 編碼/解碼Nginx 自動解碼 URI 參數,POST body 亦自動解碼直接使用解碼後的值,無需手動 ngx.unescape_uri

完整範例:統一參數獲取函數

local _M = {}

function _M.get_params()
    local method = ngx.var.request_method
    local args = {}

    if method == "GET" then
        args = ngx.req.get_uri_args()
    elseif method == "POST" then
        ngx.req.read_body()
        local content_type = ngx.var.http_content_type or ""
        if content_type:find("multipart/form-data", 1, true) then
            -- 使用 lua-resty-upload 處理 multipart
            local upload = require "resty.upload"
            local form = upload:new(8192)
            local file_fields = {}
            while true do
                local typ, res, err = form:read()
                if not typ then break end
                if typ == "header" then
                    local cd = res[2] or ""
                    local name = cd:match('name="([^"]+)"')
                    local filename = cd:match('filename="([^"]+)"')
                    if filename then
                        file_fields[name] = { filename = filename }
                        -- 這裡可串流存檔
                    else
                        args[name] = ""
                    end
                elseif typ == "body" then
                    if file_fields[current_field] then
                        -- 寫入檔案
                    else
                        args[current_field] = (args[current_field] or "") .. res
                    end
                elseif typ == "eof" then break end
            end
        else
            -- application/x-www-form-urlencoded 或 JSON
            args = ngx.req.get_post_args()
            -- 若為 JSON,需自行解碼
            if content_type:find("application/json", 1, true) then
                local cjson = require "cjson.safe"
                local body = ngx.req.get_body_data()
                if body then args = cjson.decode(body) end
            end
        end
    end
    return args
end

return _M

總結

  • 簡單場景:get_uri_args() + read_body() + get_post_args() 即可。
  • 檔案上傳/複雜表單:**必須使用 lua-resty-upload 或 lua-resty-multipart-parser**,手寫解析器極易出錯且難維護。
  • JSON API:檢測 Content-Type: application/json,用 cjson.decode(ngx.req.get_body_data())。
  • 永遠記得 ngx.req.read_body() 並處理臨時檔案情況。
copyright © 萬盛學電腦網 all rights reserved