Skip to content

Instantly share code, notes, and snippets.

@yanxurui
Last active March 31, 2017 09:28
Show Gist options
  • Save yanxurui/9fc8044141278d428255e6ff6b19f9fc to your computer and use it in GitHub Desktop.
Save yanxurui/9fc8044141278d428255e6ff6b19f9fc to your computer and use it in GitHub Desktop.
pid logs/nginx_upload.pid;
events {
worker_connections 1024;
}
http {
lua_package_path '/usr/local/lib/lua/5.1/?.lua;/blah/?.lua;;';
server {
listen 8001;
# download
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# auth
auth_basic "Restricted site";
auth_basic_user_file /opt/nginx/.htpasswd;
location /download {
alias upload;
}
location ~ ^/upload_lua(/.*)?$ {
set $store_path upload$1/;
content_by_lua_block {
local upload = require "resty.upload"
local function my_get_file_name(header)
local file_name
for i, ele in ipairs(header) do
file_name = string.match(ele, 'filename="(.*)"')
if file_name and file_name ~= '' then
return file_name
end
end
return nil
end
local chunk_size = 4096
local form = upload:new(chunk_size)
local file
local file_path
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
local file_name = my_get_file_name(res)
if file_name then
file_path = ngx.var.store_path..file_name
file = io.open(file_path, "w+")
if not file then
ngx.say("failed to open file ", file_path)
return
end
end
elseif typ == "body" then
if file then
file:write(res)
end
elseif typ == "part_end" then
if file then
file:close()
file = nil
ngx.say("upload to "..file_path.." successfully!")
end
elseif typ == "eof" then
break
else
-- do nothing
end
end
}
}
location ~ ^/delete/(.*)$ {
set $file_path upload/$1;
content_by_lua_block {
local function file_exists(path)
local file = io.open(path, "rb")
if file then file:close() end
return file ~= nil
end
if not file_exists(ngx.var.file_path) then
ngx.say("file not found: "..ngx.var.file_path)
end
r, err = os.remove(ngx.var.file_path)
if not r then
ngx.say("failed to delete: "..err)
else
ngx.say("delete successfully!")
end
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment