Hi! Thanks for visiting my blog. If you've received any value from my content would you mind supporting my new startup by downloading our browser add-on? It's called PriceBlink and makes online shopping a breeze. You can watch it in action here and download it for Chrome, Firefox, IE, or Safari by going to PriceBlink.com. Thank you and I hope you enjoy!

Rails File Upload and Content Types

Oct 07

You’re most likely going to deal with file uploads within your Rails application.  If you haven’t yet, it’s coming and hopefully this will save you some time.  I spent about an hour today racking my brain as to why I couldn’t validate different image types: image/jpeg, image/gif, and image/png.  I was doing a simple string check that looked like this:

def check_format
content_type = params[:photo].content_type
if content_type != “image/pjpeg” && content_type != “image/jpeg” && content_type != “image/gif” && content_type != “image/png”
“Error: You’ve specified the wrong file type”
end
end

This was failing repeatedly and even printing the content_type variable would yield image/jpeg.  It seemed that everything should work perfectly.  The only thing I could fathom is that there may be some extraneous garbage at the end of the string.  After doing a nice ruby chomp this solved the problem:

content_type = params[:photo].content_type.chomp

I hope this saves you some frustration in the future.

Read More