我参考了春哥的https://github.com/openresty/lua-resty-upload,进行文件的上传,发现当上传的文件太大时,比如40M,就抛出lua entry thread aborted:memory allocation error:not enough memory的错误。我的代码如下:
function _M:uploadfile(filepath)
local form, err = upload:new(chunk_size)
if not form then
ngx.log(ngx.ERR, "failed to new upload: ", err)
return false
end
form:set_timeout(timeOut) --1s
local appender = ''
local uploader, res = s3:new(aws_accesskey, aws_secretkey, chatvoc_bucket, timeOut, region, cdn_s3_endpoint)
if not uploader then
ngx.log(ngx.ERR, "s3 new failure:", res)
return false
end
local url, object_err, filename
local n=1
while true do
local typ, res, err = form:read()
if not typ then
ngx.log(ngx.ERR,"failed to read: ", err)
return false
end
if typ == "header" then
ngx.log(ngx.NOTICE, "header: ", json.encode(res))
content_type = res[2]
ngx.log(ngx.NOTICE, "content_type: ", content_type)
if content_type then
start_upload = true
end
local inputFile = [[name="input"]]
if res[1]=='Content-Disposition' and ngx.re.find(res[2] or '',inputFile) then
data_upload = true
end
elseif typ == "body" then
if start_upload == true and res then
appender = appender..res
end
if data_upload == true and res then
data_upload = false
end
elseif typ == "part_end" then
if appender ~= '' then
local data_len = string.len(appender)
ngx.log(ngx.NOTICE,"start to upload ", content_type, " len=" , data_len)
if data_len>20 then
filename = ngx.md5(appender)
print("upload file md5===="..filename)
url, object_err = uploader:upload(appender, content_type, filepath..filename)
if url then
local show = json.encode({status="0"; url = "">
ngx.log(ngx.NOTICE, "success : ", show)
else
ngx.log(ngx.ERR,"request return : ", object_err)
return false
end
else
local reason = " body too short " .. content_type
ngx.log(ngx.NOTICE, reason)
return false
end
appender = ''
start_upload = false
end
elseif typ == "eof" then
break
end
end
return true, url, filename
end