• Stars
    star
    291
  • Rank 142,563 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 16 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Adds multipart POST capability to net/http

Multipart::Post

Adds a streamy multipart form post capability to Net::HTTP. Also supports other methods besides POST.

Development Status

Features/Problems

  • Appears to actually work. A good feature to have.
  • Encapsulates posting of file/binary parts and name/value parameter parts, similar to most browsers' file upload forms.
  • Provides an UploadIO helper class to prepare IO objects for inclusion in the params hash of the multipart post object.

Installation

bundle add multipart-post

Usage

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
File.open("./image.jpg") do |jpg|
  req = Net::HTTP::Post::Multipart.new url.path,
    "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end
end

To post multiple files or attachments, simply include multiple parameters with UploadIO values:

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
req = Net::HTTP::Post::Multipart.new url.path,
  "file1" => UploadIO.new(File.new("./image.jpg"), "image/jpeg", "image.jpg"),
  "file2" => UploadIO.new(File.new("./image2.jpg"), "image/jpeg", "image2.jpg")
res = Net::HTTP.start(url.host, url.port) do |http|
  http.request(req)
end

To post files with other normal, non-file params such as input values, you need to pass hashes to the Multipart.new method.

In Rails 4 for example:

def model_params
  require_params = params.require(:model).permit(:param_one, :param_two, :param_three, :avatar)
  require_params[:avatar] = model_params[:avatar].present? ? UploadIO.new(model_params[:avatar].tempfile, model_params[:avatar].content_type, model_params[:avatar].original_filename) : nil
  require_params
end

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
Net::HTTP.start(url.host, url.port) do |http|
  req = Net::HTTP::Post::Multipart.new(url, model_params)
  key = "authorization_key"
  req.add_field("Authorization", key) #add to Headers
  http.use_ssl = (url.scheme == "https")
  http.request(req)
end

Or in plain ruby:

def params(file)
  params = { "description" => "A nice picture!" }
  params[:datei] = UploadIO.new(file, "image/jpeg", "image.jpg")
  params
end

url = URI.parse('http://www.example.com/upload')
File.open("./image.jpg") do |file|
  req = Net::HTTP::Post::Multipart.new(url.path, params(file))
  res = Net::HTTP.start(url.host, url.port) do |http|
    return http.request(req).body
  end
end

Parts Headers

By default, all individual parts will include the header Content-Disposition as well as Content-Length, Content-Transfer-Encoding and Content-Type for the File Parts.

You may optionally configure the headers Content-Type and Content-ID for both ParamPart and FilePart by passing in a parts header.

For example:

url = URI.parse('http://www.example.com/upload')

params = {
  "file_metadata_01" => { "description" => "A nice picture!" },
  "file_content_01"  => UploadIO.new(file, "image/jpeg", "image.jpg")
}

headers = {
  'parts': {
    'file_metadata_01': {
      'Content-Type' => "application/json"
      }
    }
  }

req = Net::HTTP::Post::Multipart.new(uri, params, headers)

This would configure the file_metadata_01 part to include Content-Type

Content-Disposition: form-data; name="file_metadata_01"
Content-Type: application/json
  {
    "description" => "A nice picture!" 
  }

Custom Parts Headers

For FileParts only.

You can include any number of custom parts headers in addition to Content-Type and Content-ID.

headers = {
  'parts': {
    'file_metadata_01': {
      'Content-Type' => "application/json",
      'My-Custom-Header' => "Yo Yo!"
    }
  }
}

Debugging

You can debug requests and responses (e.g. status codes) for all requests by adding the following code:

http = Net::HTTP.new(uri.host, uri.port)
http.set_debug_output($stdout)

Versioning

This library aims to adhere to Semantic Versioning 2.0.0. Violations of this scheme should be reported as bugs. Specifically, if a minor or patch version is released that breaks backward compatibility, a new version should be immediately released that restores compatibility. Breaking changes to the public API will only be introduced with new major versions.

As a result of this policy, you can (and should) specify a dependency on this gem using the Pessimistic Version Constraint with two digits of precision.

For example:

spec.add_dependency 'multipart-post', '~> 2.1'

More Repositories

1

falcon

A high-performance web server for Ruby, supporting HTTP/1, HTTP/2 and TLS.
Ruby
2,512
star
2

async

An awesome asynchronous event-driven reactor for Ruby.
Ruby
2,008
star
3

nio4r

Cross-platform asynchronous I/O primitives for scalable network clients and servers.
C
961
star
4

rubydns

A DSL for building fun, high-performance DNS servers.
Ruby
707
star
5

cool.io

Simple evented I/O for Ruby (but please check out Celluloid::IO instead)
C
693
star
6

timers

Pure Ruby timers collections suitable for use with event loops
Ruby
337
star
7

async-http

Ruby
292
star
8

localhost

Ruby
208
star
9

async-io

Concurrent wrappers for native Ruby IO & Sockets.
Ruby
205
star
10

lightio

LightIO is a userland implemented green thread library for ruby
Ruby
163
star
11

sus

Ruby
156
star
12

async-websocket

Asynchronous WebSocket client and server, supporting HTTP/1 and HTTP/2 for Ruby.
Ruby
156
star
13

utopia

A content-centric Ruby/Rack based web framework.
Ruby
139
star
14

cloudflare

An asynchronous Ruby wrapper for the CloudFlare V4 API.
Ruby
137
star
15

socketry

High-level wrappers for Ruby sockets with advanced thread-safe timeout support
Ruby
132
star
16

xrb

Ruby
102
star
17

async-dns

An asynchronous DNS resolver and server.
Ruby
96
star
18

async-redis

Ruby
83
star
19

http-accept

Parse Accept and Accept-Language HTTP headers in Ruby.
Ruby
81
star
20

async-postgres

Ruby
78
star
21

async-container

Scalable multi-thread multi-process containers for Ruby.
Ruby
78
star
22

async-http-faraday

Ruby
74
star
23

async-await

Why wait? It's available today!
Ruby
69
star
24

rackula

Generate a static site from any rack middleware.
Ruby
66
star
25

live

Ruby
64
star
26

flappy-bird

Ruby
59
star
27

io-event

C
57
star
28

async-rspec

Ruby
54
star
29

db

Event-driven database drivers for streaming queries.
Ruby
49
star
30

console

Ruby
49
star
31

roda-websockets

Asynchronous WebSockets plugin for Roda.
Ruby
47
star
32

process-metrics

Ruby
35
star
33

db-postgres

Ruby
33
star
34

async-rest

Ruby
31
star
35

lively

JavaScript
29
star
36

async-job

Ruby
27
star
37

falcon-rails-example

Ruby
25
star
38

async-pool

Provides support for connection pooling both singleplex and multiplex resources.
Ruby
24
star
39

async-process

Ruby
22
star
40

protocol-http

Ruby
22
star
41

utopia-project

JavaScript
21
star
42

guard-falcon

Ruby
21
star
43

async-actor

Ruby
19
star
44

falcon-capybara

Ruby
19
star
45

benchmark-http

Ruby
18
star
46

async-examples

Ruby
17
star
47

rspec-memory

Ruby
16
star
48

async-webdriver

Ruby
16
star
49

fiber-local

Ruby
16
star
50

traces

Ruby
15
star
51

cloudflare-dns-update

A Ruby script which can update CloudFlare periodically to provide dynamic DNS.
Ruby
15
star
52

thread-local

Ruby
14
star
53

async-sequel

Ruby
13
star
54

async-mysql

Ruby
12
star
55

falcon-benchmark

A work in progress synthetic benchmark comparing Falcon with other servers.
JavaScript
11
star
56

protocol-websocket

Provides a low-level implementation of the WebSocket protocol according to RFC6455.
Ruby
10
star
57

async-ollama

Ruby
10
star
58

db-mariadb

Ruby
10
star
59

async-job-rails-example

Ruby
10
star
60

protocol-quic

C++
9
star
61

xrb-sanitize

Sanitize markup by adding, changing or removing tags.
Ruby
9
star
62

protocol-http2

Ruby
8
star
63

async-job-adapter-active_job

Ruby
8
star
64

variant

Ruby
8
star
65

metrics

Ruby
8
star
66

rack-conform

Ruby
7
star
67

async-limiter

Async limiter for ruby.
Ruby
7
star
68

sus-vscode

TypeScript
7
star
69

xrb-rails

Ruby
7
star
70

protocol-http1

Ruby
6
star
71

async-worker

Ruby
5
star
72

memory

Ruby
5
star
73

async-http-cache

Ruby
5
star
74

live-js

JavaScript
5
star
75

db-active_record

Ruby
5
star
76

protocol-hpack

Ruby
4
star
77

db-model

Ruby
4
star
78

console-adapter-rails

Ruby
4
star
79

async-debug

JavaScript
4
star
80

io-stream

Ruby
4
star
81

protocol-rack

Ruby
4
star
82

falcon-my_api

Ruby
3
star
83

xrb-formatters

Formatters for Trenni, to assist with typical views and form based interfaces.
Ruby
3
star
84

katacoda

Katacoda Tutorials
Shell
3
star
85

rails-falcon-heroku

Ruby
3
star
86

community

3
star
87

async-bus

Ruby
3
star
88

io-endpoint

Ruby
3
star
89

traces-backend-datadog

Ruby
3
star
90

migrate

Ruby
3
star
91

utopia-falcon-heroku

JavaScript
3
star
92

xrb-vscode

2
star
93

sus-fixtures-openssl

Ruby
2
star
94

async-service

Ruby
2
star
95

lively-falcon

Ruby
2
star
96

async-cable

Ruby
2
star
97

utopia-wiki

JavaScript
1
star
98

console-adapter-sidekiq

Ruby
1
star
99

sus-fixtures-async

Ruby
1
star
100

console-output-datadog

Ruby
1
star