How to validate the content-type of a file before uploading using JavaScript? I’m not asking the extension validation. I want to validate pdf,plain text and MS word files.
I’m using a django forms.ModelForm to pass file upload widget to html. I couldn’t achieve this either on server side. Here is that question,
Maybe but it won’t give you any form of security because an attacker could use other means to upload files thus circumventing your validation.
To check the file type using the extension (which is very insecure since it’s dead easy to manipulate it), you can use JavaScript. See this question: How do I Validate the File Type of a File Upload?
[EDIT] After some googling, I found that the
inputelement has an attributeacceptwhich takes a list of mime type patterns. Unfortunately, most browsers ignore it (or only use it to tweak the file selection dialog). See this question: File input 'accept' attribute – is it useful?[EDIT 2] Right now, it seems that the File API (see “Using files from web applications“) is your only way it you really don’t want to use file extensions. Each
Fileinstance has atypeproperty which contains the mime type.But this API is work in progress, so it’s not available everywhere. And there is no guarantee that you’ll get a MIME type (the property can be
"").So I suggest this approach: Try the File API. If it’s not available or the
typeproperty is empty, use the file extension.