0

我正在尝试构建一个函数来通过多部分格式的 POST 请求发送文件,使用作为指南,但无论我对表单进行什么更改,HTTPoison 都会不断给我两个错误。他们都是

HTTPoison.post("https://api.telegram.org/myCredentials", {:multipart, form}, headers)

我的表单的三个版本和错误如下(无论我是否使用标题):

第一版和第二版(两者的错误相同):

form = [{"photo", [{"name", "myphoto.jpg"}, {:file, "files/aphoto.jpg"}]}, {"chat_id", 237799110}]
-----
form = [photo: [{"name", "myphoto.jpg"}, {:file, "files/aphoto.jpg"}], chat_id: 237799110]

这给了我这个错误:

** (FunctionClauseError) no function clause matching in anonymous fn/2 in :hackney_multipart.len_mp_stream/2
      (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_multipart.erl:159: anonymous fn({"photo", [{"name", "myphoto.jpg"}, {:file, "files/aphoto.jpg"}]}, 0) in :hackney_multipart.len_mp_stream/2
       (stdlib) lists.erl:1263: :lists.foldl/3
      (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_multipart.erl:159: :hackney_multipart.len_mp_stream/2
      (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_request.erl:319: :hackney_request.handle_body/4
      (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_request.erl:81: :hackney_request.perform/2
      (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney.erl:373: :hackney.send_request/2
    (httpoison) lib/httpoison/base.ex:432: HTTPoison.Base.request/9

第三个版本:

form = [chat_id: 237799110, photo: [{"name", "myphoto.jpg"}, {:file, "files/aphoto.jpg"}]]

这给了我以下错误:

** (ArgumentError) argument error
              :erlang.byte_size(:chat_id)
    (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_multipart.erl:255: :hackney_multipart.mp_data_header/2
    (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_multipart.erl:180: anonymous fn/3 in :hackney_multipart.len_mp_stream/2
     (stdlib) lists.erl:1263: :lists.foldl/3
    (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_multipart.erl:159: :hackney_multipart.len_mp_stream/2
    (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_request.erl:319: :hackney_request.handle_body/4
    (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney_request.erl:81: :hackney_request.perform/2
    (hackney) c:/Users/venta/projects/elixir/wrapper/deps/hackney/src/hackney.erl:373: :hackney.send_request/2

我发现在多部分 POST 请求上施加此类障碍的一系列事件中总是有不幸,因此我想听听有关导致它们的可能原因的意见。

现在,我很乐意按照这种格式从头开始编写我自己的请求,但我强迫自己使用 Elixir 及其资源,在经历了几次这样的事故后最终学会了它。

4

1 回答 1

0

查看HTTPoison.post/3. 第二个参数是一种body类型,如果您查看该类型规范的文档,您会发现:

body :: binary | {:form, [{atom, any}]} | {:file, binary}

您的第二个参数与该类型规范不匹配。您正在发送{:multipart, form}.

HTTPoison 上的这个Github 问题似乎确实建议您可以使用{:multipart, []}它,即使它与记录的规范不匹配,这里有一个 multipart 的示例测试用例

根据您的示例,可能类似于:

form = [{:file, "files/aphoto.jpg"}, {"name", "myphoto.jpg"}, {"chat_id", 237799110}]

于 2017-03-20T13:19:16.903 回答