wushifeng

  • Feb 26, 2021
  • Joined Feb 5, 2021
  • 新接触这个工具,有个上传下载文件的需求,和以前的帖子 【
    https://forum.openresty.us/d/1699-6263d824b67a7d8e42e9c4b3def3263b 上传图片的功能,需要将图片传到redis中(其实是ssdb)】有点类似
    参考这个使用的lua-resty-upload,可以获取到内容了
    现在想把图片做个处理再发到真正的服务器上【和nginx upstream类似】,各位大佬,这个该怎么处理?

    -- https://blog.csdn.net/u013412772/article/details/78626402

    --从环境变量LUA_PATH中搜索lua文件
    package.path = '../lualib/resty/?.lua;'
    --从LUA_CPATH中搜索C文件
    package.cpath = '../lualib/?.so;'

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

    local function upload()
    local upload = require("upload")
    local chunk_size = 4096

    local form, err = upload:new(nil,chunk_size,chunk_size)  
    if not form then 
        ngx.log(ngx.ERR, "failed to new upload: ", err)
        ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end
    
    local file  
    local filelen=0  
    local filename 
    local i=0  
    
    form:set_timeout(0)
    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])  
                ngx.log(ngx.DEBUG, "filename: " .. filename)
                if filename then  
                    i=i+1  
       
                    file = io.open(filename,"w+")  
                    if not file then  
                        ngx.say("failed to open file ")  
                        return  
                    end  
                else  
                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.log(ngx.DEBUG, "part_end done")
                --调用agent的bat脚本,并用agent的返回值代替下面say的内容
                --local result = io.popen('test.bat')
                --local returnValue = result:read("*all")
                --ngx.say(returnValue)
            end  
        elseif typ == "eof" then  
            break  
        else  
        end  
    end
    
    if i==0 then  
        ngx.say("please upload at least one file!")  
        return  
    end 
    
    ngx.log(ngx.DEBUG, "up done: ")

    end

    --开始调用上传文件脚本
    ngx.log(ngx.DEBUG, "-------------start execute upload_package lua script--------------")
    local request_method = ngx.var.request_method
    if "POST" == request_method then
    upload()
    end
    ngx.log(ngx.DEBUG, "-------------end execute upload_package lua script--------------")

    比如拿到这个文件内容,加些水印之类,通过lua直接上传到真正的服务器上呢?

    多谢!!!