From 21ae5cfa9293a3f78b9e75f419f4573991e1c283 Mon Sep 17 00:00:00 2001 From: Zach Gianos Date: Thu, 24 Sep 2020 15:44:01 -1000 Subject: [PATCH] Multipart/Form-Data: rewind files after read Fixes #708 --- lib/httparty/request/body.rb | 11 ++++++++++- spec/httparty/request/body_spec.rb | 2 ++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/httparty/request/body.rb b/lib/httparty/request/body.rb index ff6e408f..dd50873f 100644 --- a/lib/httparty/request/body.rb +++ b/lib/httparty/request/body.rb @@ -39,7 +39,7 @@ def generate_multipart memo += "\r\n" memo += "Content-Type: #{content_type(value)}\r\n" if file?(value) memo += "\r\n" - memo += file?(value) ? value.read : value.to_s + memo += content_body(value) memo += "\r\n" end @@ -68,6 +68,15 @@ def normalize_query(query) end end + def content_body(object) + if file?(object) + object = (file = object).read + file.rewind if file.respond_to?(:rewind) + end + + object.to_s + end + def content_type(object) return object.content_type if object.respond_to?(:content_type) mime = MIME::Types.type_for(object.path) diff --git a/spec/httparty/request/body_spec.rb b/spec/httparty/request/body_spec.rb index 4eb1e1a9..11aaac36 100644 --- a/spec/httparty/request/body_spec.rb +++ b/spec/httparty/request/body_spec.rb @@ -62,6 +62,8 @@ it { is_expected.to eq multipart_params } + it { expect { subject }.not_to change { file.pos } } + context 'when passing multipart as an option' do let(:options) { { force_multipart: true } } let(:params) do