alamodey
alamodey

Reputation: 14938

Allow only pdfs to be uploaded

How do I change this bit of code so that I only allow pdf files to be uploaded:

unless @file.content_type =~ /^image/
  errors.add(:file, "is not a recognized format")
  return false
end

Upvotes: 0

Views: 267

Answers (3)

cletus
cletus

Reputation: 625017

You've going to have to:

  1. Accept the upload;
  2. Try and open the PDF in some library;
  3. Reject the file if you can't open it.

You can't rely on the MIME type the browser gives you. The only way to do this is to verify the file. You can check the format with markers and the like but the easiest and most robust method is to open it with an appropriate library call.

Upvotes: 2

blowdart
blowdart

Reputation: 56500

Of course that code is horribly insecure. It relies on the browser sending the file to get the MIME type correct and assumes no-one has send a hacked request.

Frankly unless you open the file and parse it, knowing what makes a valid file for a particular format you cannot be sure that any file uploaded is of a particular type.

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Haven't used that, but the pdf mime type is application/pdf, so it should be just:

unless @file.content_type =~ /^application\/pdf$/

Upvotes: 2

Related Questions