Search code examples
ruby-on-railsrubycarrierwavefile-type

How to detect a file type in a Rails app?


I am using Carrierwave to upload images, documents and videos to my s3 bucket. So far uploading images and documents is fine.

What I would like to do in my view is determine the file type and then either display the image (which I can do at present) or provide an image of a document which when clicked will download/open a copy of that file for the user.

So in my view to render an image I would do this

 <% document.each do |doc| %>
   <%= link_to image_tag(doc.media_url(:thumb)) %> 
 <% end %>

But how would I go about saying

<% document.each do |doc| %>
  <% if doc.file_type == ['jpg', 'jpeg', 'png']
   <%= link_to image_tag(doc.media_url(:thumb)) %>
  <% else %>
    <%= link_to doc.media.path %> # This link downloading the file 
  <% end %>
<% end %>

Solution

  • I guess (is not a good thing to let other people guess what you should already provided in your question) you have a model Document and your uploader is media, something like this:

    class Document < ActiveRecord::Base
      mount_uploader :media, MediaUploader
    end
    

    If this is the case, for each document you get the extension (document.media.file.extension.downcase) and compare it with 'jpg', 'jpeg', 'png'

    <% document.each do |doc| %>
      <% if ['jpg', 'jpeg', 'png'].include?(document.media.file.extension.downcase) %>
        <%= link_to image_tag(doc.media_url(:thumb)) %>
      <% else %>
        <%= link_to doc.media.path %> # This link downloading the file 
      <% end %>
    <% end %>
    

    Carrierwave can give you the content type if you want it by using:

    document.media.content_type # this returns image/png for a png file ...
    

    Edit:

    I think a better way is to check it like this (it's cleaner):

    <% document.each do |doc| %>
      <% if document.media.content_type =~ /image/ %>
        <%= link_to image_tag(doc.media_url(:thumb)) %>
      <% else %>
        <%= link_to doc.media.path %> # This link downloading the file 
      <% end %>
    <% end %>