1

I am trying to read in an audio file of type wav or amr from a HTML form using Rest Client. I have the code to do this in 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.

1
  • data = params[:f1] file = File.open(data, "rb") {|io| io.read} 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 Jun 14, 2012 at 3:54

1 Answer 1

3

According to RestClient's repo:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.