提交 50fd4a3e authored 作者: AFA_ZHANRONGZHEN's avatar AFA_ZHANRONGZHEN

解决线上上传时上传目录不存在的问题

上级 279bec0a
......@@ -8,6 +8,9 @@ RUN rm /usr/local/openresty/nginx/conf/nginx.conf
COPY detect_mime_by_magic.lua /usr/local/openresty/lualib/
COPY nginx.conf /usr/local/openresty/nginx/conf/
# 创建上传目录,运行时还会按 clientId 自动创建子目录
RUN mkdir -p /var/www/html/upload && chmod 777 /var/www/html/upload
# 创建日志文件并设置权限
RUN touch /usr/local/openresty/nginx/logs/access.log && chmod 777 /usr/local/openresty/nginx/logs/access.log && \
touch /usr/local/openresty/nginx/logs/error.log && chmod 777 /usr/local/openresty/nginx/logs/error.log && \
......@@ -16,4 +19,3 @@ RUN touch /usr/local/openresty/nginx/logs/access.log && chmod 777 /usr/local/ope
# 启动openresty服务
CMD ["/usr/local/openresty/bin/openresty", "-g", "daemon off;"]
......@@ -262,6 +262,44 @@ http {
local filepath = nil
local file_size = 0
local upload_dir = "/var/www/html/upload/"
local lfs = require('lfs_ffi')
local function sanitize_path_segment(value, fallback)
if not value or value == "" then
return fallback
end
local sanitized = string.gsub(value, "[/\\:%z]", "_")
sanitized = string.gsub(sanitized, "%.%.", "_")
if sanitized == "" or sanitized == "." or sanitized == ".." then
return fallback
end
return sanitized
end
local function ensure_dir(path)
local current = ""
for segment in string.gmatch(path, "[^/]+") do
current = current .. "/" .. segment
local attr = lfs.attributes(current)
if attr then
if attr.mode ~= "directory" then
return nil, current .. " is not a directory"
end
else
local ok, mkdir_err = lfs.mkdir(current)
if not ok then
attr = lfs.attributes(current)
if not attr or attr.mode ~= "directory" then
return nil, mkdir_err
end
end
end
end
return true
end
while true do
local typ, res, read_err = form:read()
......@@ -283,12 +321,21 @@ http {
elseif typ == "body" then
if filename and not file then
if client_id then
upload_dir = upload_dir .. client_id .. "/"
upload_dir = upload_dir .. sanitize_path_segment(client_id, "anonymous") .. "/"
end
local ok, mkdir_err = ensure_dir(upload_dir)
if not ok then
ngx.log(ngx.ERR, "failed to create upload dir: ", upload_dir, ", error: ", mkdir_err)
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("failed to create upload directory")
return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
filename = sanitize_path_segment(filename, "upload.bin")
filepath = upload_dir .. filename
file = io.open(filepath, "wb")
local open_err
file, open_err = io.open(filepath, "wb")
if not file then
ngx.log(ngx.ERR, "failed to open file: ", filepath)
ngx.log(ngx.ERR, "failed to open file: ", filepath, ", error: ", open_err)
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("failed to create file")
return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论