Skip to content

Instantly share code, notes, and snippets.

@catwell
Created November 9, 2022 09:12
Show Gist options
  • Save catwell/c79055d007760b3c89ecd9240f34fb89 to your computer and use it in GitHub Desktop.
Save catwell/c79055d007760b3c89ecd9240f34fb89 to your computer and use it in GitHub Desktop.
Helping nodecentral with multipart post
-- see https://github.com/catwell/lua-multipart-post/issues/8#issuecomment-1307934583
-- fixed version (see diff)
local http = require("socket.http")
local ltn12 = require("ltn12")
local lfs = require "lfs"
http.TIMEOUT = 5
local function upload_file ( url, filename )
local fileHandle = io.open( filename,"rb")
local fileContent = fileHandle:read( "*a" )
fileHandle:close()
local boundary = 'abcd'
local header_b = 'Content-Disposition: form-data; name="document"; filename="' .. filename .. '"\r\nContent-Type: application/pdf'
local header_c = 'Content-Disposition: form-data; name="title"\r\n\r\nCompanies House File'
local header_d = 'Content-Disposition: form-data; name="correspondent"\r\n\r\n12'
local MP_b = '--'..boundary..'\r\n'..header_b..'\r\n\r\n'..fileContent..'\r\n'
local MP_c = '--'..boundary..'\r\n'..header_c..'\r\n'
local MP_d = '--'..boundary..'\r\n'..header_d..'\r\n'
local MPCombined = MP_b..MP_c..MP_d..'--'..boundary..'--\r\n'
local response_body = { }
local _, code = http.request {
url = url ,
method = "POST",
headers = { ["Content-Length"] = MPCombined:len(),
['Content-Type'] = 'multipart/form-data; boundary=' .. boundary
},
source = ltn12.source.string(MPCombined) ,
sink = ltn12.sink.table(response_body),
}
return code, table.concat(response_body)
end
local rc,content = upload_file ('http://httpbin.org/post', '/mnt/nas/10.pdf' )
print(rc,content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment