Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict file upload to some file extensions

Tags:

I am having a problem with uploading files. I want to allow users to upload files that the system allows...

For example, I allow files having an extension of *.jpg to be uploaded by users. So, in the file selection window they must see only files with the jpg extension.

How can I get this in RoR?

like image 730
Jamal Abdul Nasir Avatar asked Jan 13 '11 13:01

Jamal Abdul Nasir


2 Answers

With HTML5 you can use the :accept for limiting mime-types, like so:

 <%= file_field_tag :csv_file,  :accept => 'text/csv' %>
like image 157
Roger Avatar answered Oct 01 '22 15:10

Roger


The answer to this question is probably more related to html uploading than rails.

When you want to upload a file, you typically do an input with type="file".

This can be done in Rails by using the file_field_tag helper. It will generate an input with type="file" which can also have an accept attribute, but you can't really use that because it's not really going to have any visible effect. This attribute accepts MIME types, not extensions, and most browsers don't even use it.

The best thing you can do is probably have a javascript check the file extension before upload (after you select the file from the dialog box). Read more about it in this question.

The point is, you can't force the OS to show you only the file extensions that you want. You can either validate the extension by using JS for example, before upload, or check the contents of the file after upload, server side

like image 37
Andrei S Avatar answered Oct 01 '22 15:10

Andrei S