GithubHelp home page GithubHelp logo

faraday-multipart's Introduction

Faraday Multipart

GitHub Workflow Status Gem License

The Multipart middleware converts a Faraday::Request#body Hash of key/value pairs into a multipart form request, but only under these conditions:

  • The request's Content-Type is "multipart/form-data"
  • Content-Type is unspecified, AND one of the values in the Body responds to #content_type.

Faraday contains a couple helper classes for multipart values:

  • Faraday::Multipart::FilePart wraps binary file data with a Content-Type. The file data can be specified with a String path to a local file, or an IO object.
  • Faraday::Multipart::ParamPart wraps a String value with a Content-Type, and optionally a Content-ID.

Installation

Add this line to your application's Gemfile:

gem 'faraday-multipart'

And then execute:

bundle install

Or install it yourself as:

gem install faraday-multipart

Usage

First of all, you'll need to add the multipart middleware to your Faraday connection:

require 'faraday'
require 'faraday/multipart'

conn = Faraday.new(...) do |f|
  f.request :multipart, **options
  # ...
end

Payload can be a mix of POST data and multipart values.

# regular POST form value
payload = { string: 'value' }

# filename for this value is File.basename(__FILE__)
payload[:file] = Faraday::Multipart::FilePart.new(__FILE__, 'text/x-ruby')

# specify filename because IO object doesn't know it
payload[:file_with_name] = Faraday::Multipart::FilePart.new(
  File.open(__FILE__),
  'text/x-ruby',
  File.basename(__FILE__)
)

# Sets a custom Content-Disposition:
# nil filename still defaults to File.basename(__FILE__)
payload[:file_with_header] = Faraday::Multipart::FilePart.new(
  __FILE__,
  'text/x-ruby',
  nil,
  'Content-Disposition' => 'form-data; foo=1'
)

# Upload raw json with content type
payload[:raw_data] = Faraday::Multipart::ParamPart.new(
  { a: 1 }.to_json,
  'application/json'
)

# optionally sets Content-ID too
payload[:raw_with_id] = Faraday::Multipart::ParamPart.new(
  { a: 1 }.to_json,
  'application/json',
  'foo-123'
)

conn.post('/', payload)

Sending an array of documents

Sometimes, the server you're calling will expect an array of documents or other values for the same key. The multipart middleware will automatically handle this scenario for you:

payload = {
  files: [
    Faraday::Multipart::FilePart.new(__FILE__, 'text/x-ruby'),
    Faraday::Multipart::FilePart.new(__FILE__, 'text/x-pdf')
  ],
  url: [
    'http://mydomain.com/callback1',
    'http://mydomain.com/callback2'
  ]
}

conn.post(url, payload)
#=> POST url[]=http://mydomain.com/callback1&url[]=http://mydomain.com/callback2
#=>   and includes both files in the request under the `files[]` name

However, by default these will be sent with files[] key and the URLs with url[], similarly to arrays in URL parameters. Some servers (e.g. Mailgun) expect each document to have the same parameter key instead. You can instruct the multipart middleware to do so by providing the flat_encode option:

require 'faraday'
require 'faraday/multipart'

conn = Faraday.new(...) do |f|
  f.request :multipart, flat_encode: true
  # ...
end

payload = ... # see example above

conn.post(url, payload)
#=> POST url=http://mydomain.com/callback1&url=http://mydomain.com/callback2
#=>   and includes both files in the request under the `files` name

This works for both UploadIO and normal parameters alike.

Development

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

Then, run bin/test to run the tests.

To install this gem onto your local machine, run rake build.

Releasing a new version

To release a new version, make a commit with a message such as "Bumped to 0.0.2", and change the Unreleased heading in CHANGELOG.md to a heading like "0.0.2 (2022-01-01)", and then use GitHub Releases to author a release. A GitHub Actions workflow then publishes a new gem to RubyGems.org.

Contributing

Bug reports and pull requests are welcome on GitHub.

License

The gem is available as open source under the terms of the MIT License.

faraday-multipart's People

Contributors

imactia avatar jsvd avatar olleolleolle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

faraday-multipart's Issues

Uploading file in chunks using range header

Basic Info

  • Faraday Version: 1.9.3

Issue description

I’m trying to use Faraday to upload a file to Azure Blob Storage, which has a limit (of 268435456 bytes) for the body of each request. Larger requests must be sent in chunks using a Range or x-ms-range header. Is there a way to do that with Faraday using multipart / FilePart or otherwise?

I looked at the implementation of FilePart, which seems to support passing an IO object instead of a file path, but I’m not sure if there's a way to limit such an object to just a subsection of a file?

Here is the code I’m currently using, which works fine for files below that limit:

Faraday.new(headers: {'x-ms-blob-type': 'BlockBlob'}) {|c|
  c.request :multipart
  c.response :raise_error
  c.adapter Faraday.default_adapter
}.put(fileUploadUrl, {file: Faraday::FilePart.new(filePath, 'application/octet-stream')})

Any help would be appreciated!

Image is not saving with post request

I have author class using active storage.

              class Author < ApplicationRecord
                  has_one_attached :image
              end     

post request

             require 'faraday'
             require 'faraday/multipart'

             payload = { author: {title: "lo"} }
             payload[:author][:image] = Faraday::Multipart::FilePart.new(File.open(Rails.root.join('app', 'assets', 'images', 'about.jpg')), 'image/jpeg')

             conn.post('/api/v1/authors', payload.to_json)

My received params

         #<ActionController::Parameters {"author"=>{"title"=>"lo"}, "image"=>{"content_type"=>"image/jpeg", 
         "original_filename"=>"local.path", "local_path"=>"local.path", 
          "io"=>"/home/kashif/ticket_plot_api/app/assets/images/about.jpg", "opts"=>{}}, "controller"=>"api/v1/authors", 
           "action"=>"create"} permitted: false>

Author is saving without image

Is anything wrong?
Thanks

`Content-Disposition` header overwrite fails

I am trying to overwrite the Content-Disposition header.

For the third party API, I need a very specific filename that includes /.
I noticed the Content-Disposition header is not entirely overwritten. It still adds the default name and filename.

require 'faraday'
require 'faraday/multipart'

connection = Faraday.new(url: 'http://localhost:3000') do |connection_builder|
  connection_builder.request :multipart
  connection_builder.response :logger, nil, { headers: true, bodies: true }
end

payload = { file: Faraday::Multipart::FilePart.new('test.txt', 'text/plain', nil, 'Content-Disposition' => 'form-data; name="file"; filename="foo/bar"') }

connection.post('path', payload)

It creates

Content-Disposition: form-data; name="file"; filename="foo/bar"; name="file"; filename="test.txt"

instead of

Content-Disposition: form-data; name="file"; filename="foo/bar"

I was also trying to give the file name as a parameter to the FilePart.new.

require 'faraday'
require 'faraday/multipart'

connection = Faraday.new(url: 'http://localhost:3000') do |connection_builder|
  connection_builder.request :multipart
  connection_builder.response :logger, nil, { headers: true, bodies: true }
end

payload = { file: Faraday::Multipart::FilePart.new('test.txt', 'text/plain', 'foo/bar') }

connection.post('path', payload)

It creates

Content-Disposition: form-data; name="file"; filename="bar"

while I need

Content-Disposition: form-data; name="file"; filename="foo/bar"

Ruby 3.1.1

I am getting the warning:

/home/.../gems/faraday-multipart-1.0.4/lib/faraday/multipart.rb:17: warning: already initialized constant Faraday::Parts
/home/.../gems/faraday-0.17.5/lib/faraday/upload_io.rb:66: warning: previous definition of Parts was here
/home/.../gems/ruby-3.1.1/gems/faraday-multipart-1.0.4/lib/faraday/multipart.rb:18: warning: already initialized constant Faraday::CompositeReadIO
/home/.../gems/ruby-3.1.1/gems/faraday-0.17.5/lib/faraday/upload_io.rb:12: warning: previous definition of CompositeReadIO was here
/home/.../gems/ruby-3.1.1/gems/faraday-multipart-1.0.4/lib/faraday/multipart.rb:21: warning: already initialized constant Faraday::UploadIO
/home/.../gems/ruby-3.1.1/gems/faraday-0.17.5/lib/faraday/upload_io.rb:65: warning: previous definition of UploadIO was here

ruby 3.1.1
faraday v.0.17.5
faraday-multipart v.1.0.4

Can you please make changes to get rid of that?

Signpost issue: release a 2.0 version

There are these constants which are for the use of faraday 1.x, and we've moved them around, keeping aliases around.

It could be time to release a new major, where these are removed.

Example comment:

Aliases for Faraday v1, these are all deprecated and will be removed in v2 of this middleware

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.