1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00

Generate proper multipart body

This commit is contained in:
Nikita Misharin 2018-01-30 20:06:03 +03:00
parent 727a58294a
commit a869485199
3 changed files with 69 additions and 5 deletions

View file

@ -17,9 +17,27 @@ module HTTParty
end end
end end
def boundary
@boundary ||= "------------------------c772861a5109d5ef"
end
private private
def generate_multipart def generate_multipart
normalized_params = params.flat_map { |key, value| HashConversions.normalize_keys(key, value) }
multipart = normalized_params.inject('') do |memo, (key, value)|
memo += "--#{boundary}\n"
memo += "Content-Disposition: form-data; name='#{key}'"
memo += "; filename='#{File.basename(value)}'" if file?(value)
memo += "\n"
memo += "Content-Type: application/octet-stream\n" if file?(value)
memo += "\n"
memo += file?(value) ? value.read : value
memo += "\n"
end
multipart += "--#{boundary}--\n"
end end
def multipart? def multipart?
@ -39,7 +57,7 @@ module HTTParty
end end
def file?(object) def file?(object)
object.respond_to?(:path) && object.respond_to?(:read) object.respond_to?(:path) && object.respond_to?(:read) # add memoization
end end
def includes_hash?(object) def includes_hash?(object)
@ -54,10 +72,6 @@ module HTTParty
end end
end end
def boundary
@boundary ||= "--------------------------#{SecureRandom.urlsafe_base64(12)}"
end
attr_reader :params, :query_string_normalizer, :options attr_reader :params, :query_string_normalizer, :options
end end
end end

BIN
spec/fixtures/tiny.gif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 B

View file

@ -0,0 +1,50 @@
require_relative '../../spec_helper'
RSpec.describe HTTParty::Request::Body do
describe '#call' do
subject { described_class.new(params).call }
context 'when params is string' do
let(:params) { 'name=Bob%20Jones' }
it { is_expected.to eq params }
end
context 'when params is hash' do
let(:params) { { people: ["Bob Jones", "Mike Smith"] } }
let(:converted_params) { "people[]=Bob%20Jones&people[]=Mike%20Smith"}
it { is_expected.to eq converted_params }
context 'when params has file' do
let(:params) do
{
user: {
avatar: File.open('spec/fixtures/tiny.gif'),
first_name: 'John',
last_name: 'Doe'
}
}
end
let(:multipart_params) do
"--------------------------c772861a5109d5ef\n" \
"Content-Disposition: form-data; name='user[avatar]'; filename='tiny.gif'\n" \
"Content-Type: application/octet-stream\n" \
"\n" \
"GIF89a\u0001\u0000\u0001\u0000\u0000\xFF\u0000,\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000\u0000\u0002\u0000;\n" \
"--------------------------c772861a5109d5ef\n" \
"Content-Disposition: form-data; name='user[first_name]'\n" \
"\n" \
"John\n" \
"--------------------------c772861a5109d5ef\n" \
"Content-Disposition: form-data; name='user[last_name]'\n" \
"\n" \
"Doe\n" \
"--------------------------c772861a5109d5ef--\n"
end
it { is_expected.to eq multipart_params }
end
end
end
end