shrinerb / shrine-cloudinary

Cloudinary storage for Shrine
https://cloudinary.com/
MIT License
23 stars 6 forks source link

Cloudinary File Size Validation #5

Closed kashifnaseer closed 5 years ago

kashifnaseer commented 5 years ago

I'm trying to upload files (Image/pdf) using Shrine on cloudinary in a Ruby on Rails Application.

It seems cloudinary allows to upload 20 MB file. if users try to upload file greater than 20 MB. it throws 500 error. though i dont want to use chunk_size to allow users to upload bigger size file.

I've following uploader:

 class FileUploader < Shrine
   include TestUploader
   plugin :validation_helpers

   Attacher.validate do
     validate_max_size 5.megabytes, message: "is too large (max is 5 MB)"
   end

  plugin :upload_options, store: ->(io, context) do
   {
    type: image_type(context[:record].photoable_type)
   }
  end

  def self.image_type(photoable_type)
    if %w(ProjectEvent Modification).include?(photoable_type)
     'authenticated'
   else
      'upload'
    end
 end
end

validate_max_size only works if file which is being uploaded is less than 20 MB.

it seems, shrine validation gets executed once file gets uploaded on cloudinary. As cloudinary supports only 20 MB and it blows up before it gets uploaded in cloudinary.

Any Idea, how I can add validation for max size before it goes to cloudinary.

One approach to add validation at client side but any other way to validate it at model/ruby level using shrine-cloudinary ?

janko commented 5 years ago

Shrine assigns the file after it has been uploaded to :cache storage, and that's when validations are run. This is in order to have consistent behaviour when using direct uploads (in which case Shrine doesn't have access to the file until after it has already been uploaded to :cache storage).

You can either not set Cloudinary as your :cache storage, or validate filesize on the client side. Client side validations highly recommended for good UX, as it's not ideal to find out that your file is too large only after you've uploaded it.