--文件下载服务写到 saveRootPath .."/" .. filename 下面
function DownLoad()
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(100000)
while true do
local typ,res,err=form:read()
if not typ then
ErrorMsg="failed to read :"..err
return 1
end
if typ =="header" then
local key=res[1]
local value=res[2]
if key =="Content-Disposition" then
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
--获取文件后缀名字
fileExtension=getExtension(filename)
local linuxTime=tostring(os.time())
filePath=saveRootPath .."/" ..linuxTime..filename
fileToSave,errmsg = io.open(filePath, "w+")
--存储的文件路径
--ngx.say("failed to open file ", filePath)
if not fileToSave then
--ngx.say("failed to open file ", filePath .. errmsg)
ErrorMsg="打开文件失败"..filePath .. errmsg
return 1
end
else
ErrorMsg="请求参数找不到文件名字"
return 1
end
--跳出循环
break
end
end
end
elseif typ =="body" then
if fileToSave then
fileToSave:write(res)
fileMd5:update(res)
end
elseif typ =="part_end" then
if fileToSave then
local md5_sum=fileMd5:final()
--ngx.say("md5: ", str.to_hex(md5_sum))
fileMD532=str.to_hex(md5_sum)
fileToSave:close()
fileToSave = nil
end
elseif typ =="eof" then
break
else
ngx.log(ngx.INFO, "do other things")
end
end
return 0
end
3、tcp接收二进制数据
-- 读取byte
function readInt8(tcp)
local next, val = string.unpack(tcp:receive(1), "b")
return tonumber(val);
end
-- 读取int16
function readInt16(tcp)
local next, val = string.unpack(tcp:receive(2), "h");
return tonumber(val);
end
-- 读取int32
function readInt32(tcp)
local next, val = string.unpack(tcp:receive(4), ">i");
return tonumber(val);
end
-- 读取字符串
function readString(tcp,len)
return tostring(tcp:receive(len));
end