Parsing multipart data using HTTP.jl

I’m looking for standard function which can parse body from multipart request. I received json and csv in one multipart request. How can I parse it?

Following example is received in one multipart request. Body received from request converted to string:

-----------------------------2469282126307371221439455
Content-Disposition: form-data; name="configuration"
Content-Type: application/csv

{
  "attribute1": "value1",
  "attribute2": "value2",
  "attribute3": "value3"
}
-----------------------------2469282126307371221439455
Content-Disposition: form-data; name="file"; filename="Vieden.csv"
Content-Type: text/csv

date;value1;value2
2004-01-01 00:00:00;8;2
2004-01-01 01:00:00;7;5
2004-01-01 02:00:00;2;4

-----------------------------2469282126307371221439455--

Call HTTP.parse_multipart_form on the content. That should parse it into an array so you can get the name, contenttype, filename, and data.

3 Likes

Thank you so much for your advice. It looks it will work, but I’ve been not able to read content of this multipart array. How can I do that? How can I get data of multipart?

I tried following:

println(HTTP.parse_multipart_form(req)[2].data)
┌ Error: error handling request
│   exception =
│    ArgumentError: ensureroom failed, IOBuffer is not writeable
│    Stacktrace:
│     [1] ensureroom_slowpath(::Base.GenericIOBuffer{SubArray{UInt8,1,Array{UInt8,1},Tuple{UnitRange{Int64}},true}}, ::UInt64) at ./iobuffer.jl:303
│     [2] ensureroom at ./iobuffer.jl:325 [inlined]
│     [3] write at ./iobuffer.jl:446 [inlined]

Another output was:

println(HTTP.parse_multipart_form(req))
HTTP.Multipart[
    HTTP.Multipart(data=::Base.GenericIOBuffer{
    SubArray{UInt8,1,Array{UInt8,1},
    Tuple{UnitRange{Int64}},true}},
    contenttype="text/plain",
    contenttransferencoding="")),

    HTTP.Multipart(filename="File.csv",
    data=::Base.GenericIOBuffer{SubArray{UInt8,1,Array{UInt8,1},
    Tuple{UnitRange{Int64}},true}},
    contenttype="text/csv", contenttransferencoding=""))
]

Again, thank you very much. It is elegant solution. Finally, you can ignore previous message, I solved it:

println(String(read(HTTP.parse_multipart_form(req)[2].data)))