HTTPoison Multipart Post Request to Spree API

423 views Asked by At

While attempting to post an image to Spree's ProductImage API using HTTPoison, it's failing with the Rails error NoMethodError (undefined method 'permit' for #<ActionDispatch::Http::UploadedFile:0x007f94fa150040>). The Elixir code that I'm using to generate this request is:

 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

I can get this to work using Curl with the following call:

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

For comparison, here's a RequestBin capture of both the failing HTTPoison request followed by the successful Curl request: https://requestb.in/12et7bp1?inspect

What do I need to do in order to get HTTPoison to play nicely with this Rails API?

1

There are 1 answers

0
Dogbert On BEST ANSWER

The Content-Disposition line requires double quotes around the name and filename values. curl adds those automatically but Hackney passes the data you specify as-is, so you need to add the double quotes to the values yourself.

This:

[{"name", "image[attachment]"}, {"filename", "42757187_001_b4.jpeg"}]

should be:

[{"name", ~s|"image[attachment]"|}, {"filename", ~s|"42757187_001_b4.jpeg"|}]

(I'm only using the ~s sigil so that double quotes can be added without escaping them. ~s|""| is exactly the same as "\"\"".)