Restrict File Types in Paperclip
07/06/2010
Paperclip by thoughtbot is an easy way to handle database-driven file uploads in your Rails application. It offers most options that are necessary for standard transfers and operations. While their documentation is good, I had trouble finding out how to only allow certain file extensions to be uploaded.
The simplest way to do this is to look up the MIME types for the extensions you wish to upload. Then, add these to an array that paperclip checks on validation.
For a list of MIME types, reference this list. For example, if I want to only allow PDFs, I use application/pdf.
Then, on the model that has the attached file, add a validation supported by paperclip.
# your model has_attached_file :budget_document validates_attachment_content_type :budget_document, :content_type => [“application/pdf”]
Microsoft and .docx
The MIME type for Microsoft Word .doc files is application/msword. However, this does not work for versions of Office after 2004. After some searching I found this obnoxious type.
application/vnd.openxmlformats-officedocument.wordprocessingml.document
You’ll need to add both that MIME type and application/msword to give full support. Also, consider this for other Office formats (.xls and .xlsx, .ppt and .pptx). Check Wikipedia for some more content types for other post-2004 XML formats..
I hope this helps anyone like me coming from frameworks that have this built in.
Comments have been closed