简体   繁体   中英

Process file base on filetype [Gem Shrine]

I have a field in a form where user can upload images or document (pdf, word, excel etc). How to tell Shrine uploader to process uploaded file base on it's filetype.

class FileUploader < Shrine

 plugin :processing
 plugin :versions   
 plugin :delete_raw 
 plugin :validation_helpers

if File_is_image # <------   what to write here?

   # do image processing
   process(:store) do |io, context|
    original = io.download
    pipeline = ImageProcessing::MiniMagick.source(original)
    size_800 = pipeline.resize_to_limit!(800, 800)
    size_300 = pipeline.resize_to_limit!(300, 300)
    original.close!
   { original: io, large: size_800, small: size_300 }
  end
 else
   #do non image file processing
 end
end

or is there any better way to do this?

The io object that's yielded to the process block is a Shrine::UploadedFile object, which contains all the metadata about the original file. You use this information to skip processing based on the MIME type:

IMAGE_TYPES = %w[image/jpeg image/png image/gif]

process(:store) do |io, context|
  next io unless IMAGE_TYPES.include?(io.mime_type)

  original = io.download
  pipeline = ImageProcessing::MiniMagick.source(original)
  size_800 = pipeline.resize_to_limit!(800, 800)
  size_300 = pipeline.resize_to_limit!(300, 300)
  original.close!

  { original: io, large: size_800, small: size_300 }
end

The next ruby keyword is used here to return early from a block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM