1. 下載包安裝Openresty
openresty-1.13.6.1下載地址 https://openresty.org/download/openresty-1.13.6.1.tar.gz
安裝請自行百度。
2. 配置
2.1 nginx.conf
user root;
worker_processes 20;
error_log logs/error.log notice;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 8082;
server_name localhost;
# 最大允許上傳的文件大小
client_max_body_size 200m;
location / {
root html;
index index.html index.htm;
}
set $store_dir "/sdf/slb/openresty/nginx/html/download/"; # 文件存儲路徑
# 文件上傳接口:http://xxx:8082/upfile
location /upfile {
content_by_lua_file conf/lua/upload.lua; # 實現文件上傳的邏輯
}
# 文件下載入口: http://xxx:8082/download
location /download {
autoindex on;
autoindex_localtime on;
root html;
index index.html;
}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
2.2 upload.lua(文件位於conf/lua/upload.lua)
-- upload.lua
--==========================================
-- 文件上傳
--==========================================
local upload = require "resty.upload"
local cjson = require "cjson"
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)
-- 字符串 split 分割
string.split = function(s, p)
local rt= {}
string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
return rt
end
-- 支持字符串前后 trim
string.trim = function(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-- 文件保存的根路徑
local saveRootPath = ngx.var.store_dir
-- 保存的文件對象
local fileToSave
--文件是否成功保存
local ret_save = false
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, "=")
local 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 ret_save then
ngx.say("save file ok")
end
3. 測試
3.1 啟動openresty
sbin/nginx
3.2 上傳文件
通過地址http://192.168.23.65:8082/upfile上傳文件。

3.3 下載文件
通過http://192.168.23.65:8082/download下載文件。

x. 參考資料
http://www.codexiu.cn/nginx/blog/11024/
