Question

I have a ruby app in which freelancers can complete jobs for an employer. When the job complete, the freelancer can upload files for the employer to review. I think the freelancer should be able to upload zip files, but i don't want the freelancer to be able to upload invalid or corrupt zip files. Is there any way to stop this or check if a file is valid. Im pretty sure if there is a method or function to do this, it will be in the rubyzip library, but I've looked through their documentation and cannot find what I'm looking for.

Was it helpful?

Solution

Here is a naive solution that tries to open a Zip archive, returning true if it worked and false if an error occured:

require 'zip'

def valid_zip?(file)
  zip = Zip::File.open(file)
  true
rescue StandardError
  false
ensure
  zip.close if zip
end

I believe the ZIP format includes CRC32 checksums of its contents. If you really need it to be super fast, you could read those out of the file and check against the checksum you have computed.

OTHER TIPS

Another easy way would be be to just check with this condition, if the file is being uploaded.

file = params[:file]

file.content_type.in?(['application/zip'])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top