1

On my page I have a bunch of file upload fields (all with name="files[]" so it can be processed as a PHP array).

They are all located in one of two divs, lets call them 'div1' and 'div2'.

How can I use javascript so that onSubmit, it checks the file types and all the files in div1 can only be 'pdf', and all the files in div2' can only be 'pdf' or 'doc'?

A simple alert popup box will do (ie. "Files can only be pdf")

Any suggestions?

****************UPDATE*******************

Made a more relevant question: Add a filetype validation to phpmailer?

Community
  • 1
  • 1
Jonah Katz
  • 5,230
  • 16
  • 67
  • 90

4 Answers4

1

You can make this:

HTML:

<form method="post" enctype="multipart/form-data" name="form">

<input type="file" name="file" /><br />
<input type="file" name="file" />
<input type="submit" />
</form>

JavaScript:

   var fileInput = document.getElementsByName("file");
   for(var i = 0, len = fileInput.length; i < len; i++) {
    fileInput[i].addEventListener('change', 
        function(e) {
            if(this.files[0].name.match(/\.pdf$/) == null) {
                alert('Files can only be PDF.');
                return;
            }
        },
        false
    );
 }
The Mask
  • 17,007
  • 37
  • 111
  • 185
  • I really need it to not let the form submit if theres a non pdf file. This is only alerts them while theyre uploading.. – Jonah Katz Aug 08 '11 at 17:15
  • this alert is displayed when the file is selected(is faster,not need submit form). but, if you want so replace fileInput[i].addEventListener('change' by fileInput[i].addEventListener('submit' – The Mask Aug 08 '11 at 17:25
0

File upload elements are heavily protected in browsers, and JS has minimal access to its contents. Anything dealing with the file itself is pretty much locked off, as any hole in the system could allow a malicious site to steal files from the user's computer.

The easiest workaround is to just put up a small note next to the fields say "PDF Only!" and then use a server-side script to confirm that it is a pdf.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thats what i was thinking but then it would be annoying to distinguish between the PDF only, and PDF or DOC, but it sounds like thats whats going to have to be done. – Jonah Katz Aug 08 '11 at 17:02
  • Give the two file sections different names, then. `name="pdfs[]"` and `name="docs[]"`. – Marc B Aug 08 '11 at 17:04
  • Yeah thats what im ganna do. Right now, I have the following script using phpmailer to attach the files to an email (Actually, i think you helped me with it in a previous questions!!).. `foreach(array_keys($_FILES['files']['name']) as $key) { $source = $_FILES['files']['tmp_name'][$key]; $filename = $_FILES['files']['name'][$key]; $mail->AddAttachment($source, $filename); }` – Jonah Katz Aug 08 '11 at 17:05
  • doing you know how to add an if else before this: if the file is pdf, run the foreach, else, quit and display error: only pdf? – Jonah Katz Aug 08 '11 at 17:16
0

You can address the form element and read the name attribute, then you get the file name and can work with the file extension.

But this may only be used to make it easier to the user - so you can detect wrong file types before the uploading process.

It is NOT a protection in any way.

You can also pass the filestypes expected to the dialog itself. Most file managers and browsers respect it and display only the files of the type you want to choose, but the user can click a dropdown and select "view all files" and pic whatever files he/she want.

This is done with the accept attribute.

If you want to help the user choosing the right file both methods above are appropriate and I would even use them together.

If you want to protect your service from wrong filetypes, you have to evaluate the files server side. A file extension checking is not appropriate, there are php functions available to determine the real mimetype of a file.

The Surrican
  • 29,118
  • 24
  • 122
  • 168
0

You can check on submit for each file upload using this code:

var parts = document.getElementById('myFileField').value.split('.');
if (parts[parts.length-1] != 'pdf') {
    alert('Invalid extension. Needs to be PDF.');
}

Incorporating work by The Mask,

var fileInputs = document.getElementsByName("files[]");
for (var ele in fileInputs) {
    if (ele.parentNode.id = 'div1') {
        var parts = ele.value.split('.');
        if (parts[parts.length-1] != 'pdf') {
            alert('Invalid extension: "' + ele.value + '". Needs to be PDF.');
        }
    }
    else if (ele.parentNode.id = 'div2') {
        var parts = ele.value.split('.');
        if (parts[parts.length-1] != 'pdf' && parts[parts.length-1] != 'doc') {
            alert('Invalid extension: "' + ele.value + '". Needs to be PDF or DOC.');
        }
    }
}
Darren Griffith
  • 3,290
  • 3
  • 28
  • 35