解决nginx + lua 上传文件问题

本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/49509123 未经博主允许不得转载。
博主地址是:http://blog.csdn.net/freewebsys

1,首先不能创建upload对象

直接报错

failed to new upload: request body already exists

参考这个博客:
http://my.oschina.net/timingbob/blog/164231
就是request body 不能被使用2次造成的。

因为之前使用过一个叫 lua_need_request_body 显示 respons的post信息,和这个冲突了。去掉就好了。

这个博客上面有详细写,如何将post信息写到日志里面。
http://blog.csdn.net/jom_ch/article/details/15359129

去掉就好了。

2,将上传日志写到磁盘

参考:http://blog.csdn.net/langeldep/article/details/9628819
上面已经写的很详细了。

package.path = ‘/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;‘
package.cpath = ‘/usr/local/lib/lua/5.1/?.so;‘

local upload = require "upload"

local chunk_size = 4096  --如果不设置默认是4096.
local form = upload:new(chunk_size)
local file
local filelen=0
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/openresty/nginx/html/"
local i=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])
            if filename then
                i=i+1
                filepath = osfilepath  .. filename
                file = io.open(filepath,"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.say("file upload success")
        end
    elseif typ == "eof" then
        break
    else
    end
end
if i==0 then
    ngx.say("please upload at least one file!")
    return
end

这里需要注意一个问题,
/usr/local/openresty/nginx/html/文件夹必须是nobody权限,否则不能写文件,报错。

chown nobody:nobody /usr/local/openresty/nginx/html

上传啥都行了,也可以是图片,文件。

3,总结

本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/49509123 未经博主允许不得转载。
博主地址是:http://blog.csdn.net/freewebsys

lua+nginx上传速度还是非常快的。而且很轻量。

版权声明:本文为博主原创文章,未经博主允许不得转载。

文章来自:http://blog.csdn.net/freewebsys/article/details/49509123
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3