1. 程式人生 > >解決nginx + lua 上傳檔案問題

解決nginx + lua 上傳檔案問題

1,首先不能建立upload物件

直接報錯

failed to new upload: request body already exists

因為之前使用過一個叫 lua_need_request_body 顯示 respons的post資訊,和這個衝突了。去掉就好了。

去掉就好了。

2,將上傳日誌寫到磁碟

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,總結

lua+nginx上傳速度還是非常快的。而且很輕量。