【问题标题】:Ruby: How to post a file via HTTP as multipart/form-data?Ruby:如何通过 HTTP 将文件作为 multipart/form-data 发布?
【发布时间】:2010-09-16 02:21:56
【问题描述】:

我想做一个看起来像从浏览器发布的 HMTL 表单的 HTTP POST。具体来说,发布一些文本字段和一个文件字段。

发布文本字段很简单,net/http rdocs 中有一个示例,但我不知道如何发布文件。

Net::HTTP 看起来不是最好的主意。 curb 看起来不错。

【问题讨论】:

    标签: ruby http post


    【解决方案1】:

    我喜欢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 将帮助您入门。

    【讨论】:

    • 我收回了这一点,现在可以上传文件了。我现在遇到的问题是服务器提供了 302,而其余客户端遵循 RFC(没有浏览器这样做)并引发异常(因为浏览器应该警告这种行为)。另一种选择是路缘石,但我从来没有在窗户上安装路缘石。
    • 自首次发布以来,API 发生了一些变化,现在调用 multipart 如下:RestClient.post 'localhost:3000/foo', :upload => File.new('/path/tofile') ) 请参阅github.com/archiloque/rest-client 了解更多详情。
    • rest_client 不支持提供请求标头。许多 REST 应用程序需要/期望特定类型的标头,因此 REST 客户端在这种情况下无法工作。例如 JIRA 需要一个令牌 X-Atlassian-Token。
    • +1 用于添加 gem install rest-clientrequire 'rest_client' 部分。太多的 ruby​​ 示例忽略了该信息。
    • 作为对@onknows 评论的回应,rest-client确实现在支持用户定义的请求标头。据我所知,至少从 2010 年 4 月 30 日发布的1.5.0 开始,它就已经存在了。
    【解决方案2】:

    关于 Nick Sieger 的多部分帖子库,我不能说太多好话。

    它增加了对直接向 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|
    

    【讨论】:

    • 那个是为我做的,正是我要找的东西,也正是应该包含的东西,而不需要宝石。 Ruby 遥遥领先,却又如此落后。
    • 太棒了,这是上帝派来的!用它来猴子补丁 OAuth gem 以支持文件上传。我只花了 5 分钟。
    • @matthias 我正在尝试使用 OAuth gem 上传照片,但失败了。你能给我一些你的monkeypatch的例子吗?
    • 补丁对我的脚本来说是非常具体的(快速和肮脏的),但是看看它,也许你可以用更通用的方法来解决问题(gist.github.com/974084
    • Multipart 不支持请求标头。因此,例如,如果您想使用 JIRA REST 接口,那么 multipart 只会浪费宝贵的时间。
    【解决方案3】:

    另一个只使用标准库:

    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
    

    尝试了很多方法,但只有这对我有用。

    【讨论】:

    • 谢谢。一个小问题,第 1 行应该是:uri = URI('https://some.end.point/some/path') 这样您就可以稍后调用uri.porturi.host 而不会出错。
    • 一个小改动,如果不是临时文件并且你想从你的光盘上传一个文件,你应该使用File.open而不是File.read
    • 大多数情况下需要文件名,这是我添加的形式:form_data = [['file', File.read(file_name), {filename: file_name}]]
    • 这是正确答案。人们应该尽可能停止使用 wrapper gem,回到基础。
    • 最后,我找到了一些真正有效的代码!!!谢谢
    【解决方案4】:

    curb 看起来是一个很好的解决方案,但如果它不能满足您的需求,您可以使用Net::HTTP 来解决。多部分表单帖子只是一个经过仔细格式化的字符串,带有一些额外的标题。似乎每个需要编写多部分文章的 Ruby 程序员最终都会为它编写自己的小库,这让我想知道为什么这个功能不是内置的。也许是......无论如何,为了您的阅读乐趣,我会继续在这里给出我的解决方案。此代码基于我在几个博客上找到的示例,但我很遗憾再也找不到链接。所以我想我只需要为自己承担所有的功劳......

    我为此编写的模块包含一个公共类,用于从StringFile 对象的散列生成表单数据和标题。例如,如果您想发布一个带有名为“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
    

    【讨论】:

    • 嗨!此代码的许可证是什么?另外:在顶部的 cmets 中添加这篇文章的 URL 可能会很好。谢谢!
    • 这篇文章中的代码是在 WTFPL (sam.zoy.org/wtfpl) 下授权的。享受吧!
    • 您不应将文件流传递给FileParam 类的初始化调用。 to_multipart方法中的赋值又复制了文件内容,没必要!而是只传递文件描述符并在 to_multipart 中读取它
    • 这段代码很棒!因为它有效。 Rest-client 和 Siegers Multipart-post 不支持请求标头。如果您需要请求标头,您将在 rest-client 和 Siegers Multipart 帖子上浪费大量宝贵时间。
    • 实际上,@Onno,它现在确实支持请求标头。查看我对 eric 回答的评论
    【解决方案5】:

    这是我在尝试了这篇文章中可用的其他解决方案后的解决方案,我正在使用它在 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
    

    【讨论】:

    • 尽管看起来有点老套,但这对我来说可能是最好的解决方案,非常感谢这个建议!
    • 对于粗心的人来说,media=@... 是什么让 curl 成为一个文件,而不仅仅是一个字符串。与 ruby​​ 语法有点混淆,但 @#{photo.path} 与 #{@photo.path} 不同。这个解决方案是最好的恕我直言之一。
    • 这看起来不错,但如果你的@username 包含“foo && rm -rf /”,这会变得很糟糕:-P
    【解决方案6】:

    快进到 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

    我们甚至可以使用不支持:sizeIO来流式传输表单数据。

    希望这个答案真的可以帮助某人:)

    附:我只在 ruby​​ 2.3.1 中测试过这个

    【讨论】:

      【解决方案7】:

      好的,下面是一个使用遏制的简单示例。

      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]
      

      【讨论】:

        【解决方案8】:

        在我覆盖 RestClient::Payload::Multipart 中的 create_file_field 之前,restclient 对我不起作用。

        它在应该是 'Content-Disposition: form-data' 的每个部分中创建了一个 'Content-Disposition: multipart/form-data'

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

        如果你需要,我的 fork 在这里:git@github.com:kcrawford/rest-client.git

        【讨论】:

        • 这个在最新的restclient中已经修复了。
        【解决方案9】:

        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
        

        【讨论】:

        • 什么是 StreamPart 类?
        【解决方案10】:

        还有 nick sieger 的 multipart-post 可以添加到可能的解决方案的长列表中。

        【讨论】:

        • multipart-post 不支持请求标头。
        • 实际上,@Onno,它现在确实支持请求标头。查看我对 eric 回答的评论
        【解决方案11】:

        我遇到了同样的问题(需要发布到 jboss 网络服务器)。 Curb 对我来说很好,除了当我在代码中使用会话变量时它导致 ruby​​ 崩溃(ubuntu 8.10 上的 ruby​​ 1.8.7)。

        我深入研究了 rest-client 文档,找不到多部分支持的迹象。我尝试了上面的 rest-client 示例,但 jboss 说 http 帖子不是多部分的。

        【讨论】:

          【解决方案12】:

          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

          【讨论】:

            【解决方案13】:

            使用http.rbgem:

            HTTP.post("https://here-you-go.com/upload",
                      form: {
                        file: HTTP::FormData::File.new(file_path)
                      })
            

            Details

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-08-10
              • 1970-01-01
              • 2019-05-03
              相关资源
              最近更新 更多