1

我正在尝试使用 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 的相对新手。

4

1 回答 1

2

根据RestClient 的回购

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
于 2012-11-06T13:07:45.383 回答