J.Ensk J.Ensk - 3 months ago 36
HTTP Question

how to http:post file with httpc:request in erlang?

I used to code like this :

inets:start(),
ssl:start(),
ParaUrl = io_lib:format("http://xxx/passport?accessn=~s",[Access]),
ParaStr = io_lib:format("id=~p",[Id]),
RegUsr = httpc:request(post,{ParaUrl, [],"application/x-www-form-urlencoded", list_to_binary(ParaStr)},[],[])


but it's just for string not binary file, can anyone tell me how to post binary file with httpc:request?

Answer

Inspired by [http://code.activestate.com/recipes/146306/] , Altered by [http://lethain.com/formatting-multipart-formdata-in-erlang/] Thanks!

format_multipart_formdata(Boundary, Fields, Files) ->
    FieldParts = lists:map(fun({FieldName, FieldContent}) ->
        [lists:concat(["--", Boundary]),
            lists:concat(["Content-Disposition: form-data; name=\"",atom_to_list(FieldName),"\""]),
            "", FieldContent]
                           end, Fields),

    FieldParts2 = lists:append(FieldParts),


    FileParts = lists:map(fun({FieldName, FileName, FileContent}) ->

        [lists:concat(["--", Boundary]),
            lists:concat(["Content-Disposition: form-data; name=\"",atom_to_list(FieldName),"\"; filename=\"",FileName,"\""]),
            lists:concat(["Content-Type: ", "application/octet-stream"]), "", FileContent]
                          end, Files),
    FileParts2 = lists:append(FileParts),
    EndingParts = [lists:concat(["--", Boundary, "--"]), ""],
    Parts = lists:append([FieldParts2, FileParts2, EndingParts]),
    string:join(Parts, "\r\n").

Usage:

{ok,BinStream} = file:read_file("./images/avatar.png"),
Data = binary_to_list(BinStream), 
Boundary = "------WebKitFormBoundaryUscTgwn7KiuepIr1",
ReqBody = format_multipart_formdata(Boundary, [{uid,"123"}], [{avatar, "avatar", Data}]),
ContentType = lists:concat(["multipart/form-data; boundary=", Boundary]),
ReqHeader = [{"Content-Length", integer_to_list(length(ReqBody))}],

inets:start(),
ParaUrl = string:join(["http://www.example.com/avatar?access_token=",binary_to_list(token)],""),
RegUsr = httpc:request(post,{ParaUrl, ReqHeader,ContentType, ReqBody},[],[])