Created
November 9, 2022 09:12
-
-
Save catwell/c79055d007760b3c89ecd9240f34fb89 to your computer and use it in GitHub Desktop.
Helping nodecentral with multipart post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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