split form upload and wx upload, refactor file structure
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
-- 指定模块引用目录,否则无法加载同目录下的其他文件
|
||||
--package.path = package.path .. ';/usr/local/opt/openresty/nginx/scripts/?.lua';
|
||||
package.path = package.path .. ';<SCRIPT_PATH>/?.lua';
|
||||
|
||||
local upload = require "resty.upload"
|
||||
local uuid = require "resty.jit-uuid"
|
||||
local verify = require('jwt_verify')
|
||||
local create_task = require("create_task")
|
||||
|
||||
local authHeader = ngx.req.get_headers().Authorization
|
||||
local sudoerToken = ngx.req.get_headers().HtySudoerToken
|
||||
|
||||
verify(authHeader, sudoerToken)
|
||||
|
||||
local function read_form_file()
|
||||
local chunk_size = 4096
|
||||
local form, err = upload:new(chunk_size)
|
||||
if not form then
|
||||
ngx.log(ngx.ERR, "failed to new upload: ", err)
|
||||
ngx.exit(500)
|
||||
end
|
||||
uuid.seed()
|
||||
|
||||
local file_dir = ngx.var.tmp_file_dir
|
||||
local file
|
||||
local file_name
|
||||
local files = {}
|
||||
|
||||
while true do
|
||||
local type, res, err = form:read()
|
||||
|
||||
if not type then
|
||||
ngx.say("FAILED TO READ *UPLOAD IMAGE* -> ", err)
|
||||
return
|
||||
end
|
||||
|
||||
if type == "header" then
|
||||
--"Content-Disposition","form-data; name=\"files[]\"; filename=\"Song-of-joy.png\""
|
||||
--"Content-Type","image\/png"
|
||||
local key = res[1]
|
||||
local val = res[2]
|
||||
if key == "Content-Type" then
|
||||
local ext = ngx.re.match(val, [[(\w+)\/(\w+)]], "jo")[2]
|
||||
file_name = uuid() .. "." .. ext
|
||||
end
|
||||
|
||||
if file_name then
|
||||
file = io.open(file_dir .. "/" .. file_name, "w+")
|
||||
ngx.log(ngx.INFO, "FILENAME -> ", file_name)
|
||||
if not file then
|
||||
ngx.say("failed to open file ", file_name)
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
elseif type == "body" then
|
||||
if file then
|
||||
file:write(res)
|
||||
-- sha1:update(res)
|
||||
end
|
||||
elseif type == "part_end" then
|
||||
if file then
|
||||
file:close()
|
||||
table.insert(files, file_name)
|
||||
end
|
||||
-- 这里要重置一下file_name,否则后面的文件保存时会导致前面已保存的文件变成空文件
|
||||
-- file:flush() 和 io.flush() 都没效果
|
||||
file_name = nil
|
||||
file = nil
|
||||
elseif type == "eof" then
|
||||
create_task(files, authHeader, sudoerToken)
|
||||
break
|
||||
else
|
||||
-- do nothing
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
read_form_file()
|
||||
|
||||
Reference in New Issue
Block a user