尝试使用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
我可以通过以下调用使用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
为了进行比较,这里是一个RequestBin捕获失败的HTTPoison请求,然后是成功的Curl请求: https://requestb.in/12et7bp1?inspect
为了让HTTPoison能够很好地使用这个Rails API,我需要做些什么?
答案 0 :(得分:4)
Content-Disposition
行requires double quotes around the name
and filename
values。 curl
会自动添加这些内容,但Hackney会按原样传递您指定的数据,因此您需要自己将双引号添加到值中。
此:
[{"name", "image[attachment]"}, {"filename", "42757187_001_b4.jpeg"}]
应该是:
[{"name", ~s|"image[attachment]"|}, {"filename", ~s|"42757187_001_b4.jpeg"|}]
(我只使用~s
sigil,因此可以在不转义双引号的情况下添加双引号。~s|""|
与"\"\""
完全相同。)