HTTPoison 向 Spree API 发送多部分请求

Chr*_*son 1 elixir spree httpoison

尝试使用 HTTPoison 将图像发布到 Spree 的ProductImage API时,失败并出现 Rails 错误NoMethodError (undefined method 'permit' for #<ActionDispatch::Http::UploadedFile:0x007f94fa150040>)。我用来生成此请求的 Elixir 代码是:

 def create() do
    data = [
      {:file, "42757187_001_b4.jpeg",
      {"form-data", [{"name", "image[attachment]"}, {"filename", "42757187_001_b4.jpeg"}]},
          [{"Content-Type", "image/jpeg"}]
        }, {"type", "image/jpeg"}
    ]

    HTTPoison.post!("http://localhost:3000/api/v1/products/1/images", {:multipart, data}, ["X-Spree-Token": "5d096ecb51c2a8357ed078ef2f6f7836b0148dbcc536dbfc", "Accept": "*/*"])
  end
Run Code Online (Sandbox Code Playgroud)

我可以通过以下调用使用 Curl 使其工作:

curl -i -X POST \
  -H "X-Spree-Token: 5d096ecb51c2a8357ed078ef2f6f7836b0148dbcc536dbfc" \
  -H "Content-Type: multipart/form-data" \
  -F "image[attachment]=@42757187_001_b4.jpeg" \
  -F "type=image/jpeg" \
  http://localhost:3000/api/v1/products/1/images
Run Code Online (Sandbox Code Playgroud)

为了进行比较,下面是失败的 HTTPoison 请求和成功的 Curl 请求的 RequestBin 捕获: https://requestb.in/12et7bp1?inspect

为了让 HTTPoison 与这个 Rails API 很好地配合,我需要做什么?

Dog*_*ert 5

Content-Disposition行需要将用双引号引起来namefilenamecurl自动添加这些值,但哈克尼按原样传递您指定的数据,因此您需要自己将双引号添加到值中。

这:

[{"name", "image[attachment]"}, {"filename", "42757187_001_b4.jpeg"}]
Run Code Online (Sandbox Code Playgroud)

应该:

[{"name", ~s|"image[attachment]"|}, {"filename", ~s|"42757187_001_b4.jpeg"|}]
Run Code Online (Sandbox Code Playgroud)

(我只使用~s印记,以便可以添加双引号而不转义它们。~s|""|与 完全相同"\"\""。)