How to send a base 64 encoded image to an API endpoint in Ruby on Rails

Fatos Morina
Jul 23, 2017 · 2 min read
Img source: java67.com

I recently had to upload an image to an API endpoint in Rails, and did not found that much material online, so I decided to write this article describing how I managed to do this.

I was building an API that had to interact with an authentication micro service, where the request parameter was a Multipart image of a user file that should then be encoded in base 64 and get uploaded to AWS.

Basically, what I did was very simple:

file = request[:image]
json["data"] = Base64.encode64(File.read(file.path))

Let’s describe each part.

First we need to get the parameter in our controller:

file = request[:image]

Then we need to read our file from the file path:

File.read(file.path)

Finally, we need to encode our content in base 64:

json[:data] = Base64.base64(File.read(file.path))

This is all we need to do.

I am also sending other parameters, such as filename and content_type:

Here is the whole method whose result is then added as a request parameter and sent to the other API:

def prepare_json_image(file)
json = {}
json["filename"] = file.original_filename
json["content_type"] = file.content_type
json["data"] = Base64.encode64(File.read(file.path))
json
end

As you can see, it is very simple and easy to be implemented with so many great pre-existing functionalities that are available in Ruby on Rails.

Mozaix LLC

Web and mobile development company trying to make the IT world a better workplace.

Fatos Morina

Written by

Data Scientist | Software Engineer | Writer at https://www.fatosmorina.com/

Mozaix LLC

Web and mobile development company trying to make the IT world a better workplace.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade