With Carrierwave and minimagic can I test if the file is imageable?

424 views Asked by At

I have a file uploader that is intended to take pdf, rft, txt, doc, docx

I want to create a thumbnail when I can.
txt files and pdf's work great with this

process resize_to_fill: [150, 150], convert: :jpg 

doc and docx's will fail when the runs

Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: MiniMagick::Invalid

I have two questions about this.
1. How can I handle this error before it becomes an error? Or at least let the user save their attachment, without spitting back at them.
2. Is there a way to convert a doc/docx to a thumbnail (not with calls to ourside services?)

1

There are 1 answers

0
Logan Rice On

To upload the file and only create a thumbnail when possible you can add a version with conditional processing. Then create a method that checks for valid content types.

class FileUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  include CarrierWave::MimeTypes 

  version :thumb, if: :imageable? do 
    process resize_to_fill: [150,150]
    process convert: "jpg"
  end

  protected

  def imageable?(new_file)
    is_image = new_file.content_type.start_with? 'image'
    is_pdf = new_file.content_type.end_with? 'pdf'
    is_image || is_pdf
  end
end