views:

157

answers:

2

How to validate corrupt image file while uploading using Rails

  • if the corrupted jpg or png file (or change the extension of any other type of file to jpg)

    the system will have to show error during upload

+1  A: 

You can check the MIME type to make sure that it's not file with a changed extension by using the mime-types library.

type = MIME::Types.type_for(your_file.original_filename).first

I'm not sure how that would work with corrupted/broken files though. Make sure to look into Paperclip for uploading files, as it's ridiculously easy to set up and use.

Mike Trpcic
+2  A: 

I second Mike Trpcic's suggestion on using Paperclip, I have a screencast on the topic.

If you are using that and doing some graphic conversion (such as making thumbnails) you can look for PaperclipCommandLineError exception. I believe that is triggered if the conversion fails which would be the case if ImageMagick was not able to read the graphic (due to corruption or incorrect type).

If you rescue Paperclip::PaperclipCommandLineError you can present a nice error to the user.

ryanb