I'm developing a Ruby on Rails application that requires file uploading/downloading. For the upload part i used the gem carrierwave since it's very easy to use and flexible. The problem is: once i uploaded the file, i need to know a few things: i.e. if it's a pdf instead of downloading the file i show it inline,and the same goes for an image. How do i get the file extension and how can i do it to send the file to a user?? Any feedback is appreciated Thanks!!
Asked
Active
Viewed 1.9k times
2 Answers
40
Determine file extension (I suppose a name for mounted uploader is 'file'):
file = my_model.file.url
extension = my_model.file.file.extension.downcase
Then prepare mime and disposition vars:
disposition = 'attachment'
mime = MIME::Types.type_for(file).first.content_type
if %w{jpg png jpg gif bmp}.include?(extension) or extension == "pdf"
disposition = 'inline'
end
(add other extensions if you want).
And then send the file:
send_file file, :type => mime, :disposition => disposition

bender
- 1,430
- 10
- 14
-
Thank you very much, i like the style of your solution, and it worked perfectly. Again, thanks for the reply!! – Wiggin Jul 25 '12 at 09:19
-
where exactly in the rails project files you place the disposition and MIME type vars? – maumercado Oct 12 '12 at 02:02
5
Once you have uploaded a file, the name is stored in the database. This also includes the extension. Assuming you have a User
model with an uploader mounted as asset
, then you can get it as:
user.asset.file.extension
As for sending it to the user, if you call user.asset_url
, it will give you the URL where the file is uploaded. The user can use that link to get the file. Or am I misunderstanding what you mean by "send the file to a user"?

Stefan Kanev
- 3,030
- 22
- 17
-
Thanks for replying!! well, i want to make the user download the file. You know, donwload dialog (open with.. or keep it or in chrome case keep or reject.)I thought that with a simple send_file with parameters would be okay. – Wiggin Jul 25 '12 at 08:57
-
Well, just link to the file then. You can get the url with `user.asset_url`. – Stefan Kanev Jul 25 '12 at 09:15
-
-
when in context of an uploader all you need to call is `file.extension` e.g. in `def filename; ["original", file.extension].join('.'); end` – equivalent8 Aug 16 '21 at 14:52