Sending Binary Data over the Network with Json
First, you need to open the file. Since the file is binary, you have to open it with an additional “b” flag.
Here i am sending a zip file
f = File.open("path/myzip.zip", "rb")
Next, you have to do binary-to-text encoding on the binary file because the JSON will complain if you try to feed it a binary string. To overcome this obstacle, you need to apply Base64 encoding.
file_content = Base64.b64encode(f.read())
After you have a text representation of the data, you can then use JSON to package it, you can use to_json to convert in to json
{:file=>file_content}.to_json
In your Rails application you can do this like
render :layout=>false , :json => {:file=> file_content}.to_json
Comments
Post a Comment