网上搜索了好久lua发送文件的资料,发现openresty的库里面没有post 文件的函数,没办法,只能自己实现
首先,需要了解http发送文件的原理,具体请转到http://blog.youkuaiyun.com/terry7/article/details/49464335
下面是实现的代码
步骤一:新建comm.lua,里面写httpPostFile函数
local http = require("resty.http")
local TIMEOUT = 30 --默认超时时间
--生成随机函数,需要放大后处理
function random(n,m)
math.randomseed(os.clock()*math.random(100000,9000000)*math.random(100000,900000))
return math.random(n,m)
end
--生成指定长度的随机字符串
function random_str(len)
local str = ""
for i=1,len,1 do
str = str .. string.char(random(97,122))
end
return str
end
function httpPostFile(url, filepath, timeout)
local httpc = http.new()
--如果不传入timeout,则使用默认时间
local timeout = timeout or TIMEOUT
http:set_timeout(timeout*1000)
--生成随机字符串,用于区分各个文件的内容间隔
local boundary = random_str(12)
local str = ""
--读取文件内容
local f = io.open(filepath, 'r')
local data = f:read("*all")
f:close()
--组建body
str = str .. "------------------------------" .. boundary .. "\r\n"