centeros6.5使用openresty实现文件上传,并按不同时期存储在不同目录,
centeros6.5使用openresty实现文件上传,并按不同时期存储在不同目录,
1,openresty的环境配置与安装:
如果您之前对openresty没有过了解,请查看章亦春大神的官方文档:
http://openresty.org/cn/installation.html
里面有openresty的安装配置,教程,(请安装最新版本)。
安装配置完成后,重启nginx服务器
/usr/local/openresty/nginx/sbin/nginx -s reload
启动nginx服务器的时候报如下错误:
nginx: [error] open() "/usr/local/openresty/nginx/logs/nginx.pid" failed (2: No such file or directory)
执行下面的命令:
/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
2,lua语言来处理:
把下面的 savefile.lua 文件放到了/usr/local/openresty/nginx/conf/lua/ (没有。则创建)目录中
package.path = '/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;'
package.cpath = '/usr/local/lib/lua/5.1/?.so;'
local upload = require "upload"
local chunk_size = 4096
local form = upload:new(chunk_size)
local file
local filelen=0
form:set_timeout(0) -- 1 sec
local filename
function get_filename(res)
local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')
if filename then
return filename[2]
end
end
local osfilepath = "/usr/local/openresty/nginx/html/"
local i=0
while true do
local typ, res, err = form:read()
if not typ then
ngx.say("failed to read: ", err)
return
end
--下面的代码段校验,目录是否存在,不存在则创建,这里是按照不同秒数的字符串创建文件夹
local time=os.time()
--把 local str=os.date("%x",time) 注释去掉,
--并把 local newpath=osfilepath .. time .. "/"
--改为 local newpath=osfilepath .. str .. "/"
--可以按照不同日创建文件夹,如"2016/10/28"文件夹
--local str=os.date("%x",time)
local newpath=osfilepath .. time .. "/"
local dfile = io.open(newpath, "w+")
if not dfile then
ngx.say("dfile--"..newpath)
local md="mkdir "
local mdpath=md .. newpath
os.execute(mdpath)
else
dfile:close()
end
--到这里,校验结束。
if typ == "header" then
if res[1] ~= "Content-Type" then
filename = get_filename(res[2])
if filename then
i=i+1
filepath = newpath .. filename
file = io.open(filepath,"w+")
if not file then
ngx.say("failed to open file ")
return
end
else
end
end
elseif typ == "body" then
if file then
filelen= filelen + tonumber(string.len(res))
file:write(res)
else
end
elseif typ == "part_end" then
if file then
file:close()
file = nil
ngx.say("file upload success")
end
elseif typ == "eof" then
break
else
end
end
if i==0 then
ngx.say("please upload at least one file!")
return
end
3,配置/usr/local/openresty/nginx/conf/nginx.conf 文件:
在server中添加以下内容:
location /uploadfile
{
content_by_lua_file 'conf/lua/savefile.lua';
}
4,上传测试:
curl -F "action=uploadfile" -F "file=@/root/tmp/test.txt" http://127.0.0.1/uploadfile
file=@/root/tmp/test.txt 这里是要上传的文件的路径。
5,日志查看:
在/usr/local/openresty/nginx/logs下有日志文件access.log和error.log:
开启两个终端查看日志:
查看access.log: tail -f access.log
查看error.log: tail -f error.log
评论暂时关闭