views:

8126

answers:

5

I have a simple HTML upload form, and I want to specify a default extension ("*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly.

<form enctype="multipart/form-data" action="uploader.php" method="POST">
Upload DRP File:
<input name="Upload Saved Replay" type="file" accept="*.drp"/><br />
<input type="submit" value="Upload File" />
</form>

Edit I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.

+2  A: 

The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.

Additionally, it appears that most browsers may not honor this attribute.

The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.

Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.

Brian Cline
+3  A: 

Check my answer to this question: File input ‘accept’ attribute - is it useful?

CMS
A: 

The accept attribute specifies a comma-separated list of content types (MIME types) that the target of the form will process correctly. Unfortunately this attribute is ignored by all the major browsers, so it does not affect the browser's file dialog in any way.

John Topley
A: 

You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.

You can start with something like this:

<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
    alert(document.someform.file1.value)
}
</script>

I agree with alexmac - do it server-side as well.

Diodeus
A: 

I wouldnt use this attribute as most browsers ignore it as CMS points out.

By all means use client side validation but only in conjunction with server side. Any client side validation can be got round.

Slightly off topic but some people check the content type to validate the uploaded file. You need to be careful about this as an attacker can easily change it and upload a php file for example. See the example at: http://www.scanit.be/uploads/php-file-upload.pdf

alexmac