使用ngx_lua发送文件给服务器

网上搜索了好久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"
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值