Files
resty_functions/prod/upload/upload.lua
T

80 lines
2.1 KiB
Lua
Raw Normal View History

2021-08-28 22:01:00 +08:00
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)
2021-09-02 12:40:51 +08:00
uuid.seed()
2021-08-28 22:01:00 +08:00
2021-09-04 12:38:15 +08:00
local task_server = ngx.var.task_server
local file_dir = ngx.var.tmp_file_dir
2021-08-28 22:01:00 +08:00
local file
local file_name
local files = {}
2021-09-04 12:38:15 +08:00
2021-08-28 22:01:00 +08:00
while true do
local typ, res, err = form:read()
if not typ then
2021-09-04 12:38:15 +08:00
ngx.say("failed to read: ", err)
return
2021-08-28 22:01:00 +08:00
end
if typ == "header" then
2021-09-06 18:56:59 +08:00
--"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]
2021-09-06 18:56:59 +08:00
file_name = string.format("%s/%s.%s", file_dir, uuid(), ext)
end
2021-08-28 22:01:00 +08:00
if file_name then
file = io.open(file_name, "w+")
if not file then
ngx.say("failed to open file ", file_name)
return
end
end
2021-09-04 12:38:15 +08:00
elseif typ == "body" then
2021-08-28 22:01:00 +08:00
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
2021-08-28 22:01:00 +08:00
file = nil
elseif typ == "eof" then
local http = require "resty.http"
local httpc = http.new()
2021-09-06 18:56:59 +08:00
local remote_url = string.format("%s/api/v1/ts/create_task", task_server)
local res, err = httpc:request_uri(
2021-09-04 12:38:15 +08:00
remote_url,
{
method = "POST",
2021-09-06 18:56:59 +08:00
headers = {
host = "ngx"
},
body = {
cjson.encode({task_type = 1, data = files})
},
}
)
if 201 ~= res.status then
ngx.log(ngx.ERR, "create task failed", err)
ngx.say(err)
ngx.exit(res.status)
end
ngx.say(res.body)
2021-08-28 22:01:00 +08:00
break
else
-- do nothing
end
end