ルビィ:HTTP 経由でファイルを multipart/form-data として投稿するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/184178

  •  06-07-2019
  •  | 
  •  

質問

ブラウザから投稿された HMTL フォームのように見える HTTP POST を実行したいと考えています。具体的には、いくつかのテキスト フィールドとファイル フィールドを投稿します。

テキスト フィールドの投稿は簡単です。net/http の Rdoc に例がありますが、それと一緒にファイルを投稿する方法がわかりません。

Net::HTTP は最良のアイデアとは思えません。 縁石 見た目は良いです。

役に立ちましたか?

解決

RestClient が好きです。マルチパートフォームデータのようなクールな機能でnet / httpをカプセル化します。

require 'rest_client'
RestClient.post('http://localhost:3000/foo', 
  :name_of_file_param => File.new('/path/to/file'))

ストリーミングもサポートしています。

gem install rest-client で開始できます。

他のヒント

Nick Siegerのmultipart-postライブラリについて十分なことを言えません。

Net :: HTTPに直接マルチパートポストのサポートを追加し、境界や、自分とは異なる目標を持つ大きなライブラリについて手動で心配する必要がなくなります。

README

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

ここでライブラリを確認できます。 http://github.com/nicksieger/multipart-post

または以下でインストール:

$ sudo gem install multipart-post

SSL経由で接続している場合、次のように接続を開始する必要があります。

n = Net::HTTP.new(url.host, url.port) 
n.use_ssl = true
# for debugging dev server
#n.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = n.start do |http|

curb は優れたソリューションのように見えますが、ニーズに合わない場合は、 Net :: HTTP 実行できます>。マルチパートフォームポストは、いくつかの余分なヘッダーを含む慎重にフォーマットされた文字列です。マルチパート投稿を行う必要のあるすべてのRubyプログラマーは、そのために独自の小さなライブラリを作成することになりそうです。多分それは...とにかく、あなたの読書の喜びのために、私は先に進み、ここで私の解決策を与えます。このコードは、いくつかのブログで見つけた例に基づいていますが、リンクがもう見つからないことを残念に思います。だから私は自分のためにすべてのクレジットを取る必要があると思います...

このために作成したモジュールには、 String および File オブジェクトのハッシュからフォームデータとヘッダーを生成するための1つのパブリッククラスが含まれています。たとえば、「title」という名前の文字列パラメータを使用してフォームを投稿する場合、 " document"という名前のファイルパラメータを使用して、次の操作を実行します。

#prepare the query
data, headers = Multipart::Post.prepare_query("title" => my_string, "document" => my_file)

次に、 Net :: HTTP

で通常の POST を実行します。
http = Net::HTTP.new(upload_uri.host, upload_uri.port)
res = http.start {|con| con.post(upload_uri.path, data, headers) }

または他の方法で POST を実行します。ポイントは、 Multipart が送信する必要のあるデータとヘッダーを返すことです。以上です!シンプルでしょ? Multipartモジュールのコードは次のとおりです( mime-types gemが必要です):

# Takes a hash of string and file parameters and returns a string of text
# formatted to be sent as a multipart form post.
#
# Author:: Cody Brimhall <mailto:brimhall@somuchwit.com>
# Created:: 22 Feb 2008
# License:: Distributed under the terms of the WTFPL (http://www.wtfpl.net/txt/copying/)

require 'rubygems'
require 'mime/types'
require 'cgi'


module Multipart
  VERSION = "1.0.0"

  # Formats a given hash as a multipart form post
  # If a hash value responds to :string or :read messages, then it is
  # interpreted as a file and processed accordingly; otherwise, it is assumed
  # to be a string
  class Post
    # We have to pretend we're a web browser...
    USERAGENT = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6"
    BOUNDARY = "0123456789ABLEWASIEREISAWELBA9876543210"
    CONTENT_TYPE = "multipart/form-data; boundary=#{ BOUNDARY }"
    HEADER = { "Content-Type" => CONTENT_TYPE, "User-Agent" => USERAGENT }

    def self.prepare_query(params)
      fp = []

      params.each do |k, v|
        # Are we trying to make a file parameter?
        if v.respond_to?(:path) and v.respond_to?(:read) then
          fp.push(FileParam.new(k, v.path, v.read))
        # We must be trying to make a regular parameter
        else
          fp.push(StringParam.new(k, v))
        end
      end

      # Assemble the request body using the special multipart format
      query = fp.collect {|p| "--" + BOUNDARY + "\r\n" + p.to_multipart }.join("") + "--" + BOUNDARY + "--"
      return query, HEADER
    end
  end

  private

  # Formats a basic string key/value pair for inclusion with a multipart post
  class StringParam
    attr_accessor :k, :v

    def initialize(k, v)
      @k = k
      @v = v
    end

    def to_multipart
      return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"\r\n\r\n#{v}\r\n"
    end
  end

  # Formats the contents of a file or string for inclusion with a multipart
  # form post
  class FileParam
    attr_accessor :k, :filename, :content

    def initialize(k, filename, content)
      @k = k
      @filename = filename
      @content = content
    end

    def to_multipart
      # If we can tell the possible mime-type from the filename, use the
      # first in the list; otherwise, use "application/octet-stream"
      mime_type = MIME::Types.type_for(filename)[0] || MIME::Types["application/octet-stream"][0]
      return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"; filename=\"#{ filename }\"\r\n" +
             "Content-Type: #{ mime_type.simplified }\r\n\r\n#{ content }\r\n"
    end
  end
end

この投稿で利用可能な他のものを試した後の私のソリューションは、TwitPicで写真をアップロードするために使用しています:

  def upload(photo)
    `curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`
  end

標準ライブラリのみを使用する別のライブラリ:

uri = URI('https://some.end.point/some/path')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'If you need some headers'
form_data = [['photos', photo.tempfile]] # or File.open() in case of local file

request.set_form form_data, 'multipart/form-data'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| # pay attention to use_ssl if you need it
  http.request(request)
end

多くのアプローチを試しましたが、これだけがうまくいきました。

OK、これは縁石を使用した簡単な例です。

require 'yaml'
require 'curb'

# prepare post data
post_data = fields_hash.map { |k, v| Curl::PostField.content(k, v.to_s) }
post_data << Curl::PostField.file('file', '/path/to/file'), 

# post
c = Curl::Easy.new('http://localhost:3000/foo')
c.multipart_form_post = true
c.http_post(post_data)

# print response
y [c.response_code, c.body_str]

2017 年に早送りすると、 ruby stdlib net/http 1.9.3以降、これが組み込まれています

Net::HTTPRequest#set_form):application/x-www-form-urlencoded と multipart/form-data の両方をサポートするために追加されました。

https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html#method-i-set_form

使用することもできます IO サポートしないもの :size フォームデータをストリーミングします。

この回答が誰かに本当に役立つことを願っています:)

追伸Ruby 2.3.1でのみこれをテストしました

restclientは、RestClient :: Payload :: Multipartのcreate_file_fieldをオーバーライドするまで機能しませんでした。

&#8216; Content-Disposition:form-data&#8217; <はず> 'Content-Disposition:multipart / form-data' を各部分に作成していました

http://www.ietf.org/rfc/rfc2388.txt

私のフォークは、必要に応じてここにあります:git@github.com:kcrawford / rest-client.git

NetHttpを使用したソリューションには、大きなファイルを送信するときにファイル全体を最初にメモリに読み込むという欠点があります。

少し遊んだ後、次の解決策を思いつきました。

class Multipart

  def initialize( file_names )
    @file_names = file_names
  end

  def post( to_url )
    boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'

    parts = []
    streams = []
    @file_names.each do |param_name, filepath|
      pos = filepath.rindex('/')
      filename = filepath[pos + 1, filepath.length - pos]
      parts << StringPart.new ( "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" + param_name.to_s + "\"; filename=\"" + filename + "\"\r\n" +
      "Content-Type: video/x-msvideo\r\n\r\n")
      stream = File.open(filepath, "rb")
      streams << stream
      parts << StreamPart.new (stream, File.size(filepath))
    end
    parts << StringPart.new ( "\r\n--" + boundary + "--\r\n" )

    post_stream = MultipartStream.new( parts )

    url = URI.parse( to_url )
    req = Net::HTTP::Post.new(url.path)
    req.content_length = post_stream.size
    req.content_type = 'multipart/form-data; boundary=' + boundary
    req.body_stream = post_stream
    res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }

    streams.each do |stream|
      stream.close();
    end

    res
  end

end

class StreamPart
  def initialize( stream, size )
    @stream, @size = stream, size
  end

  def size
    @size
  end

  def read ( offset, how_much )
    @stream.read ( how_much )
  end
end

class StringPart
  def initialize ( str )
    @str = str
  end

  def size
    @str.length
  end

  def read ( offset, how_much )
    @str[offset, how_much]
  end
end

class MultipartStream
  def initialize( parts )
    @parts = parts
    @part_no = 0;
    @part_offset = 0;
  end

  def size
    total = 0
    @parts.each do |part|
      total += part.size
    end
    total
  end

  def read ( how_much )

    if @part_no >= @parts.size
      return nil;
    end

    how_much_current_part = @parts[@part_no].size - @part_offset

    how_much_current_part = if how_much_current_part > how_much
      how_much
    else
      how_much_current_part
    end

    how_much_next_part = how_much - how_much_current_part

    current_part = @parts[@part_no].read(@part_offset, how_much_current_part )

    if how_much_next_part > 0
      @part_no += 1
      @part_offset = 0
      next_part = read ( how_much_next_part  )
      current_part + if next_part
        next_part
      else
        ''
      end
    else
      @part_offset += how_much_current_part
      current_part
    end
  end
end

ニックシーガーの multipart-post もあり、可能な解決策の長いリストに追加しています。

同じ問題が発生しました(jboss Webサーバーに投稿する必要があります)。コードでセッション変数を使用すると、Rubyがクラッシュする(ubuntu 8.10でruby 1.8.7)ことを除いて、縁石はうまく機能します。

rest-client docsを掘り下げましたが、マルチパートサポートの兆候が見つかりませんでした。上記のrest-clientの例を試しましたが、jbossはhttpの投稿はマルチパートではないと述べました。

multipart-post gemはRails 4 Net :: HTTPで非常によく機能します。他の特別なgemはありません

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

https://github.com/Feuda/multipart-post/tree / patch-1

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top