Img source:

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(

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:

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

json[:data] = Base64.base64(

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(

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.