Files
resty_functions/scripts/form_upload_to_combine.lua
T
2023-11-06 01:22:29 +08:00

84 lines
2.7 KiB
Lua

-- 指定模块引用目录,否则无法加载同目录下的其他文件
--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 "lib.my_uuid"
local http = require "resty.http"
local cjson = require "cjson"
local verify = require('lib.jwt_verify')
local create_task = require("lib.create_task")
local TaskTypes = require 'lib.task_type'
local httpc = http:new()
local authHeader = ngx.req.get_headers().Authorization
local sudoerToken = ngx.req.get_headers().HtySudoerToken
verify(httpc, 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, "TO COMBINE 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
local task_text = cjson.encode({ task_type = TaskTypes.UPLOAD_PICTURE, payload = { images = files } })
create_task(httpc, task_text, authHeader, sudoerToken)
break
else
-- do nothing
end
end
end
read_form_file()