Jamal Abdul Nasir
Jamal Abdul Nasir

Reputation: 2667

Restrict file upload to some file extensions

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?

Upvotes: 25

Views: 19655

Answers (5)

Christopher Oezbek
Christopher Oezbek

Reputation: 26473

You can use the :accept for limiting file extensions. For instance:

<%= file_field_tag 'files[]', :multiple => true, :accept => '.jpg' %>

Upvotes: 0

Ankit Wadhwana
Ankit Wadhwana

Reputation: 445

<%= file_field_tag :file, accept: 'image/jpg'%>

on rails 5.2

Upvotes: 1

Andrei S
Andrei S

Reputation: 6516

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

Upvotes: 11

Roger
Roger

Reputation: 7610

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

 <%= file_field_tag :csv_file,  :accept => 'text/csv' %>

Upvotes: 22

fl00r
fl00r

Reputation: 83680

Firstly you can use extname method to validate files you are saving. http://apidock.com/ruby/File/extname/class

Secondly I use Paperclip gem https://github.com/thoughtbot/paperclip for uploading files. There is validate_attachment_content_type method for validating extensions: http://rdoc.info/gems/paperclip/2.3.8/Paperclip/ClassMethods#validates_attachment_content_type-instance_method

Upvotes: 8

Related Questions