tags:

views:

1094

answers:

4

I'm storing some files in my database and since I'm storing them in binary format and not keeping any other information, I have to make sure that all of them are in the same format so that I'll be able to "serve" them later (If there's a simple way to infer the file type from a byte array, please tell, but that's not the focus here).

So, what I need to do is validate every file that is uploaded to make sure it's on the required format.

I've set up a FieldTemplate with a FileUpload control and a CustomValidator:

<asp:FileUpload ID="FileUpload" runat="server" />&nbsp;


<asp:CustomValidator
    ID="CustomValidator1"
    runat="server"
    ErrorMessage="PDF only."
    ControlToValidate="FileUpload"
    OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

What I'm missing is the code to place in that CustomValidator1_ServerValidate method that checks the uploaded file to make sure it's in the right format (PDF in this case).

Thanks in advance.

+1  A: 

Another thread discussing this here

RandomNoob
Don't know how I missed it, I did a bunch of searches.Anyway, that thread focus mainly on validating by checking the file extension on the client side. I was trying to do something a bit more robust, by using the ContentType. And I can do it on the server, no problem.
Farinha
+1  A: 

Use the FileUpload.PostedFile.ContentType property to validate the MIME type ( should be application/pdf ). For security reasons, also validate that the file extension is appropriate ( .pdf ). You could have a static hashtable containing mappings from MIME type to file extension(s) and use as lookup to validate an extension.

baretta
A: 

The FileUpload.PostedFile.ContentType was exactly what I was looking for.

Just a heads-up to whoever is trying to do the same thing: it seems that the MIME type for PDF files can be "application/pdf" or "text/pdf", so be sure to check for both.

Farinha
A: 

User can spoof it. In the solution above has no validation of the actual bytes content. I can send you executable and disguise it as pdf and this will not catch it.

ary