How to return image from a Rails API?

Viewed 1945

Just to clarify, I am trying to return images, that I have stored using active storage on my machine, through the localhost for development testing purposes. I am not trying to render images from localhost unto the internet.

So I have a model that has a has_one_attached relation to an image, called sample.

meal.rb:

    include Rails.application.routes.url_helpers
    has_one_attached :sample

    def get_sample_url
        url_for(self.sample)
    end 

So I use the get_sample_url, above, to get the images. It has been returning a path and I just assumed that it was working and have built my entire API using similar code and getting similar links. But when I put the link in the browser, it doesn't return anything.

The link returned is http://localhost:3001/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--c83eba36bfec0607652b47d857104d3cf9e88009/cute%20owl.jpg

I want to know: Is the ideal way to return images from a Rails API? Why the link is not returning my images?

1 Answers

What is the ideal way to return images from a Rails API?

It depends.

If we are talking about JSON it does not actually have a binary type so in order to include an image in the JSON response itself you would need to base64 encode it. Since this increases the size of the file dramatically its something you would really only consider for simple images like bar codes or QR codes.

For most "normal" images like user avatar and the like you want to just include a URL in the json that the client can request when/if it needs the image.

If the scope of your application is small you can use file system storage. But Rails is not going to make your localhost available to the whole internet.

But if you want your app to scale use a cloud CDN that is fast and distributed. I would consider using a CDN with an existing adapter instead of Cloudinary if you want to spend time doing something else then setup.

Related