Ruby rest-client file upload as multipart form data with basic authenticaion

跟風遠走 提交于 2019-12-03 12:12:59

问题


I understand how to make an http request using basic authentication with Ruby's rest-client

response = RestClient::Request.new(:method => :get, :url => @base_url + path, :user => @sid, :password => @token).execute

and how to post a file as multipart form data

RestClient.post '/data', :myfile => File.new("/path/to/image.jpg", 'rb')

but I can't seem to figure out how to combine the two in order to post a file to a server which requires basic authentication. Does anyone know what is the best way to create this request?


回答1:


How about using a RestClient::Payload with RestClient::Request... For an example:

request = RestClient::Request.new(
          :method => :post,
          :url => '/data',
          :user => @sid,
          :password => @token,
          :payload => {
            :multipart => true,
            :file => File.new("/path/to/image.jpg", 'rb')
          })      
response = request.execute



回答2:


Here is an example with a file and some json data:

require 'rest-client'

payload = {
  :multipart => true,
  :file => File.new('/path/to/file', 'rb'),
  :data => {foo: {bar: true}}.to_json
      }

r = RestClient.post(url, payload, :authorization => token)



回答3:


RestClient API seems to have changed. Here's the latest way to upload a file using basic auth:

response = RestClient::Request.execute(
  method: :post,
  url: url,
  user: 'username',
  password: 'password',
  timeout: 600, # Optional
  payload: {
    multipart: true,
    file: File.new('/path/to/file, 'rb')
  }
)



回答4:


The newest best way may be that: the link is enter link description here

  RestClient.post( url,
  {
    :transfer => {
      :path => '/foo/bar',
      :owner => 'that_guy',
      :group => 'those_guys'
    },
     :upload => {
      :file => File.new(path, 'rb')
    }
  })


来源:https://stackoverflow.com/questions/11388090/ruby-rest-client-file-upload-as-multipart-form-data-with-basic-authenticaion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!