简体   繁体   English

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

[英]How to POST binary data using Rest Client?

I am trying to read in an audio file of type wav or amr from a HTML form using Rest Client. 我正在尝试使用Rest Client从HTML表单中读取wav或amr类型的音频文件。 I have the code to do this in PHP. 我有在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.");
       }
  }

I need to convert this code to Ruby and I am having trouble doing so as I am a relative novice when it comes to Ruby. 我需要将此代码转换为Ruby,但这样做比较麻烦,因为我是Ruby的相对新手。

According to RestClient's repo : 根据RestClient的回购协议

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

This snippet of code simply sends a file: 此代码段只是发送一个文件:

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

So I assume all you still need to do is to set the headers: 因此,我假设您仍然需要设置标题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM