Skip to content

Commit 598775f

Browse files
authored
Show usage of flat_encode option in README
Fixes lostisland/faraday#1375
1 parent bbaa465 commit 598775f

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

README.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,16 @@ gem install faraday-multipart
4242
First of all, you'll need to add the multipart middleware to your Faraday connection:
4343

4444
```ruby
45+
require 'faraday'
4546
require 'faraday/multipart'
4647

4748
conn = Faraday.new(...) do |f|
48-
f.request :multipart
49+
f.request :multipart, **options
4950
# ...
5051
end
5152
```
5253

54+
5355
Payload can be a mix of POST data and multipart values.
5456

5557
```ruby
@@ -91,6 +93,50 @@ payload[:raw_with_id] = Faraday::Multipart::ParamPart.new(
9193
conn.post('/', payload)
9294
```
9395

96+
### Sending an array of documents
97+
98+
Sometimes, the server you're calling will expect an array of documents or other values for the same key.
99+
The `multipart` middleware will automatically handle this scenario for you:
100+
101+
```ruby
102+
payload = {
103+
files: [
104+
Faraday::Multipart::FilePart.new(__FILE__, 'text/x-ruby'),
105+
Faraday::Multipart::FilePart.new(__FILE__, 'text/x-pdf')
106+
],
107+
url: [
108+
'http://mydomain.com/callback1',
109+
'http://mydomain.com/callback2'
110+
]
111+
}
112+
113+
conn.post(url, payload)
114+
#=> POST url[]=http://mydomain.com/callback1&url[]=http://mydomain.com/callback2
115+
#=> and ncludes both files in the request under the `files[]` name
116+
```
117+
118+
However, by default these will be sent with `files[]` key and the urls with `url[]`, similarly to arrays in url parameters.
119+
Some servers (e.g. Mailgun) expect each document to have the same parameter key insted.
120+
You can instruct the `multipart` middleware to do so by providing the `flat_encode` option:
121+
122+
```ruby
123+
require 'faraday'
124+
require 'faraday/multipart'
125+
126+
conn = Faraday.new(...) do |f|
127+
f.request :multipart, flat_encode: true
128+
# ...
129+
end
130+
131+
payload = ... # see example above
132+
133+
conn.post(url, payload)
134+
#=> POST url=http://mydomain.com/callback1&url=http://mydomain.com/callback2
135+
#=> and ncludes both files in the request under the `files` name
136+
```
137+
138+
This works for both `UploadIO` and normal parameters alike.
139+
94140
## Development
95141

96142
After checking out the repo, run `bin/setup` to install dependencies.

0 commit comments

Comments
 (0)