views:

38

answers:

3

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
+2  A: 

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

unless @file.content_type =~ /^application\/pdf$/
Matthew Flaschen
+3  A: 

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.

blowdart
This is correct. Of course, you can first reject files based on mime type, but eventually you will have to use a secure parser and handle any errors.
Matthew Flaschen
+2  A: 

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.

cletus
Why can't you rely on the MIME type?
alamodey
Because I could use ANY web library to upload a virus-laden .exe or .msi (or non-MS equivalent) and claim it's application/pdf. Depending on the web browser, a subsequent download could harm a naive user.
Chris Dolan