简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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