【问题标题】:Net::HTTP::Post::Multipart file parameter with file on the flyNet::HTTP::Post::Multipart 文件参数与文件动态
【发布时间】:2012-11-22 23:34:44
【问题描述】:

我正在尝试执行 Net::HTTP:POST::Multiport 并将一些文件格式的文本发送到 API。

我从我的数据库中获取数据,我不想创建物理文件,我想使用数据动态创建一个文件并将其发送到 API。 现在我有

request = Net::HTTP::Post::Multipart.new("my/path", 
                                           { "file" => UploadIO.new(file, "text/plain", file.path), 
                                             "merge" => false, 
                                             "ignore_missing" => false, 
                                             "label" => "", 
                                             "low_priority" => false })

这里file 应该是我从磁盘读取的文件对象或IO 根据http://rubydoc.info/gems/multipart-post/1.1.0/UploadIO#initialize-instance_method,知道如何从一堆字符串创建 JSON IO,而无需创建一个文件并写入它?

还有知道如何通过httmultiparty 做到这一点吗?

【问题讨论】:

    标签: ruby-on-rails ruby multipart httparty net-http


    【解决方案1】:

    是的,你可以通过“httmultiparty”来做到这一点
    在您的控制器方法中添加 -

    class SomeController <  ApplicationController
       def send_file
           response = Foo.post('/', :query => {
                      :file => File.new('abc.txt') # Generate your file here
           })
           # here Foo is class_name which is present in model/foo.rb
           response.code # it give response code success or failure.
       end
    end
    

    在模型中只需创建任何文件,让 foo.rb 并添加以下代码 -

    require 'httmultiparty'
    class Foo
       include HTTMultiParty
       base_uri 'my/path' #url where to send file 
    end  
    

    您只需执行 params[:file] 即可在您的路径上获取文件。我认为这对你有帮助。

    【讨论】:

    • 实际上 abc.txt 不会生成我的文件,它只是加载磁盘上已经存在的文件,这是我的问题
    • 所以 File.new('abc.txt', 'w') 确实会生成一个文件,但它也会将文件写入磁盘,这是我试图避免的
    • 您可以在那边提供生成的文件临时路径。
    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多