Skip to content

Instantly share code, notes, and snippets.

@CurtHagenlocher
Created July 20, 2015 20:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CurtHagenlocher/b21ce9cddf54e3807317 to your computer and use it in GitHub Desktop.
Save CurtHagenlocher/b21ce9cddf54e3807317 to your computer and use it in GitHub Desktop.
Using multipart/form-data with Power Query. This assumes that any files being uploaded are textual; changing this to support arbitrary binary data is possible, but wasn't interesting to me.
let
Web.MultiPartPost = (url as text, parts as record) as binary =>
let
unique = Text.NewGuid(),
boundary = "--" & unique,
crlf = "#(cr)#(lf)",
item = (name, value) =>
let
filename = Value.Metadata(value)[name]?,
contentType = Value.Metadata(value)[type]?,
line1 = "Content-Disposition: form-data; name=""" & name & """" &
(if filename = null then "" else "; filename=""" & filename & """"),
line2 = if contentType = null then {} else { "Content-Type: " & contentType },
lines = { boundary, line1 } & line2 & { "", value }
in
Text.Combine(lines, crlf) & crlf,
body = Text.Combine(List.Transform(Record.FieldNames(parts), each item(_, Record.Field(parts, _)))) & boundary & "--" & crlf
in
Web.Contents(url, [
Headers=[#"Content-Type"="multipart/form-data; boundary=" & unique],
Content=Text.ToBinary(body)
]),
fileContents =
"{""code"": ""15315""}
{""code"": ""526133""}
{""code"": ""43011""}
{""code"": ""83988""}
{""code"": ""182347""}",
parts = [
id = "c9c43e63-9372-441c-9ab7-c5e66d7da371",
file = fileContents meta [name="upload.txt", type="text/plain"],
locale = "en-US"
],
Result = Web.MultiPartPost("http://foo.com/bar/baz", parts)
in
Result
@pbihani7
Copy link

What is the purpose of creating filecontents when we are passing the file? should it not pick data from the file?

@CurtHagenlocher
Copy link
Author

What is the purpose of creating filecontents when we are passing the file? should it not pick data from the file?

You could get the contents any way you wanted -- File.Contents, AzureStorage.BlobContents, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment