Files
resty_functions/upload.lua
T
2021-11-18 20:02:01 +08:00

97 lines
2.9 KiB
Lua

local upload = require "resty.upload"
local uuid = require "resty.jit-uuid"
local cjson = require "cjson"
local chunk_size = 4096
local form = upload:new(chunk_size)
uuid.seed()
TaskTypes = {
NOOP = 'NOOP',
UPLOAD_PICTURE = 'UPLOAD_PICTURE'
}
local task_server = ngx.var.task_server
local file_dir = ngx.var.tmp_file_dir
local file
local file_name
local files = {}
while true do
local typ, res, err = form:read()
if not typ then
ngx.say("FAILED TO READ *UPLOAD IMAGE* -> ", err)
return
end
if typ == "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 typ == "body" then
if file then
file:write(res)
-- sha1:update(res)
end
elseif typ == "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 typ == "eof" then
local http = require "resty.http"
local httpc = http.new()
local remote_url = string.format("%s/api/v1/ts/create_task", task_server)
ngx.log(ngx.INFO, 'remote_url -> ', remote_url)
ngx.log(ngx.INFO, 'Authorization -> ', ngx.req.get_headers().Authorization)
ngx.log(ngx.INFO, 'HtySudoerToken -> ', ngx.req.get_headers().HtySudoerToken)
local body_text = cjson.encode({task_type = TaskTypes.UPLOAD_PICTURE, data = {images = files}})
ngx.log(ngx.INFO, 'UPLOAD_PICTURE *body_text* ->', body_text)
local res, err = httpc:request_uri(
remote_url,
{
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Authorization"] = ngx.req.get_headers().Authorization,
["HtySudoerToken"] = ngx.req.get_headers().HtySudoerToken
},
body = body_text,
}
)
if 201 ~= res.status then
ngx.log(ngx.ERR, "TASK CREATE *FAILED*", err)
ngx.say(err)
ngx.exit(res.status)
end
ngx.say(res.body)
break
else
-- do nothing
end
end