Richlewis
Richlewis

Reputation: 15384

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 %>

Upvotes: 1

Views: 2447

Answers (2)

cristian
cristian

Reputation: 8744

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 %>

Upvotes: 3

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16515

Well, in linux, I believe in Mac too, there is the utility to determine the type of file:

$ file filename.jpg
filename: JPEG image data, JFIF standard 1.02
$ file ./шрифты/шрифты/page-0020.png
filename.png: PNG image, 2512 x 3270, 8-bit grayscale, non-interlaced

so in ruby you are able to issue %x() method to get the info:

def type filename
   res = %x(file "#{File.expand_path(filename)}")
   m = res.match(/(.*): (.*)$/).to_a.last.split(' ').first.downcase
end

so it will return:

type "filename.jpg" # => jpeg
type "filename.png" # => png

For windows some people should use mingw/cygwin installations.

Upvotes: 1

Related Questions