Nginx+lua restricts file type request method to realize image upload

You can also add redis to prevent frequent requests

local upload = require "upload"
local method = ngx.var.request_method
if method ~='POST' then
    ngx.say("method is not allowed")
    return
end
local chunk_size = 4096
local form = upload:new(chunk_size)
local file
local filelen=0
if nil == form then 
    ngx.say("upload file is null")
    return
end
form:set_timeout(0) -- 1 sec
local filename


function get_filename(res)
    local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')
    if filename then 
        return filename[2]
    end
end


local osfilepath = "/usr/local/nginx-1.12.2/html/icon/"
local i=0
--ngx.say(ngx.var.args) -- querystring
local emailMd5 = ngx.var.args
if nil == emailMd5 then
    ngx.say("email error")
    return
elseif string.len(emailMd5)~=32 then
    ngx.say('email error')
    return
else
    ngx.say("email md5:"..emailMd5)
end
while true do
    local typ, res, err = form:read()
    if not typ then
        ngx.say("failed to read: ", err)
        return
    end
    if typ == "header" then
        if res[1] ~= "Content-Type" then
            filename = get_filename(res[2])
            if filename then
                i=i+1
                filepath = osfilepath  .. emailMd5..".jpg"
                file = io.open(filepath,"wb+")
                if not file then
                    ngx.say("failed to open file "..filepath.."\r\n")
                    return
                end
            else
            end
        else
        --文件类型
            if res ~= nil then
                ngx.say(""..res[2])
                if string.match(res[2],'image/') == nil then
                    ngx.say("only support image")
                    return
                end
            end
        end
    elseif typ == "body" then
        if file then
            filelen= filelen + tonumber(string.len(res))    
            file:write(res)
        else
        end
    elseif typ == "part_end" then
        if file then
            file:close()
            file = nil
            ngx.say("file upload success")
            return
        end
    elseif typ == "eof" then
        break
    else
    end
end
if i==0 then
    ngx.say("please upload at least one file!")
    return
end

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324440092&siteId=291194637