Serving an image with Grape

1.1k views Asked by At

I have a GET service who should serve an image. Following the Grape readme: https://github.com/intridea/grape#user-content-sending-raw-or-no-data

get :image do
  content_type 'application/octet-stream'
  File.binread "image.png"
end

But when I download the image is missing its extension (.png) and the filename.

I have tried too:

get :image do
  content_type 'image/png'
  File.binread "image.png"
end

But it returns the error:

Encoding::UndefinedConversionError ("\x89" from ASCII-8BIT to UTF-8)

How should send the image for avoiding to lose extension and filename?

2

There are 2 answers

0
IBmeister On

For anyone who might run into this in the future, the correct solution is adding a line for the header property, like so:

header['Content-Disposition'] = "attachment; filename=filename.png"

"attachment" can be switched to "inline" if you want the file displayed on the browser.

0
debbie On

You cando like this, Add content_type :png, "image/png" before it.

content_type :png, "image/png"
get :image do
  content_type 'image/png'
  File.binread "image.png"
end