TAGS :Viewed: 7 - Published at: a few seconds ago

[ How to save and return a file ]

I'm trying to save an image to a database with sinatra-activerecord to be returned later. Currently (I think) saving is functioning correctly:

Photo.create(photo:params[:image][:tempfile].read)

But when I try to return it the browser shows a not an image icon, and when I actually go to the url that the browser is going to I see a mess of random characters. How can I get this to work and why isn't what I have working?

Here is how I am trying to return it:

file = Tempfile.new('photo')
file.write(Photo.find(params[:id]).photo)
return file

Answer 1


Wow, I can't believe you didn't know this already @thesecretmaster, it's obvious that you should have been saving the submitted content-type (params[:image][:type]) and then when you return file you should have set content_type <previously saved content-type> before retuning the stored binary image. Also, in case you weren't already doing this, you have to store params[:image][:tempfile].read with the type binary in activerecord, or you might get some variety of AttributteError.