如何使用Rest Client发布二进制数据?

时间:2012-06-14 02:18:59

标签: ruby http post binary-data rest-client

我正在尝试使用Rest Client从HTML表单中读取类型为wav或amr的音频文件。我有在PHP中执行此操作的代码。

$filename = $_FILES['f1']['name'];

public function getFile($filename) {
      if (file_exists($filename)) {
          $file_binary = fread(fopen($filename, "r"), filesize($filename));
          return $file_binary;
       } else {
          throw new Exception("File not found.");
       }
  }

我需要将此代码转换为Ruby,因为我是Ruby的相对新手,所以我很难这样做。

1 个答案:

答案 0 :(得分:1)

根据RestClient's repo

def self.post(url, payload, headers={}, &block)
    Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers, &block)
  end

这段代码只发送一个文件:

file = File.open('path/to/file.extension', 'r')
RestClient.post("your_url_to_the_endpoint", file)

所以我假设你还需要做的就是设置标题:

begin 
file = File.open(params[:f1], "rb") 
url = "...." 
response = RestClient.post url, file, {:Authorization => "Bearer #{@access_token}", :Accept => 'application/json', :Content_Type => 'audio/wav'} 

rescue => e 
@error = e.message 
ensure 
return erb :speech 
end