Openresty三 | 上传文件
上传文件接口
nginx.conf 的server 增加一个location:
location /upload
{
resolver 8.8.8.8 ipv6=off;
content_by_lua_file lua/upload.lua;
}
upload.lua
lua
-- upload.lua
--==========================================
-- 文件上传
--==========================================
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(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
form:set_timeout(1000)
-- 文件保存的根路径
local saveRootPath = "./download/"
-- 保存的文件对象
local fileToSave
--文件是否成功保存
local ret_save = false
local filename = ""
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
-- 开始读取 http header
-- 解析出本次上传的文件名
local key = res[1]
local value = res[2]
if key == "Content-Disposition" then
-- 解析出本次上传的文件名
-- form-data; name="testFileName"; filename="testfile.txt"
local kvlist = string.split(value, ';')
for _, kv in ipairs(kvlist) do
local seg = string.trim(kv)
if seg:find("filename") then
local kvfile = string.split(seg, "=")
filename = string.sub(kvfile[2], 2, -2)
if filename then
fileToSave = io.open(saveRootPath .. filename, "w+")
if not fileToSave then
ngx.say("failed to open file ", filename)
return
end
break
end
end
end
end
elseif typ == "body" then
-- 开始读取 http body
if fileToSave then
fileToSave:write(res)
end
elseif typ == "part_end" then
-- 文件写结束,关闭文件
if fileToSave then
fileToSave:close()
fileToSave = nil
end
ret_save = true
elseif typ == "eof" then
-- 文件读取结束
break
else
ngx.log(ngx.INFO, "do other things")
end
end
if not ret_save then
ngx.say("save file error")
return
end
filename = saveRootPath..filename
ngx.say("save file success filename: " .. filename)
curl测试
$ curl -X POST -F 'data=@foo.txt' http://127.0.0.1:9001/upload
- foo.txt: 本地文件名字
更改上传目录权限
更改目录所有者命令
chown -R 用户名称 目录名称
更改目录权限命令
chmod -R 755 目录名称
--完--
- 原文作者: 留白
- 原文链接: https://zfunnily.github.io/2021/12/openresty-upload/
- 更新时间:2024-04-16 01:01:05
- 本文声明:转载请标记原文作者及链接