4

I have 4 file input tags to upload files as follows,

Left File : <input type="file" name="dataFile1" id="fileChooser1" />
Right File : <input type="file" name="dataFile2" id="fileChooser2" />
Config File : <input type="file" name="dataFile3" id="fileChooser3" />
<button type="button" id="execute" onclick="ValidateFile()">Click to Upload files</button>

Now, I want to make sure that only distinct files are are being uploaded.

How do I do this is JS/JQ without using third party plugins?

I've used,

var FileName1 = document.getElementById('fileChooser1').value;
var FileName2 = document.getElementById('fileChooser2').value;

if(FileName1 == FileName2)
 {
   alert("Same files cannot be uploaded");
 }

But this checks only for the names of the files that are being uploaded, if two files with different names but same content are uploaded then they are being identified as different files.

  • 2
    It seems to me that you're looking for FileReader: https://developer.mozilla.org/en-US/docs/Web/API/FileReader. Here's a simple tutorial about using it: http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html (scroll to The JavaScript FileList and File Objects) – eithed Mar 28 '14 at 10:24
  • 1
    One of the modest solutions is to check the names as well as their sizes. I think in javascript you can check for the files' sizes using `if(FileName1.files[0].size == FileName2.files[0].size){...}` – Omoro Mar 28 '14 at 10:46
  • 1
    A good starting point -> http://stackoverflow.com/questions/768268/how-to-calculate-md5-hash-of-a-file-using-javascript – blgt Mar 28 '14 at 10:48

1 Answers1

0

You should be able to get the file size property from the input field with jQuery. See How to check file input size with jQuery?.

If you compare those, you'd have an extra check that you aren't uploading the same files. Although no guarantee.

In your specific case you can get this and more extra information like this:

//Check file data before execution
$('#execute').live('click', function() {
   console.log($("#fileChooser1")[0].files[0]);
   console.log($("#fileChooser2")[0].files[0]);
   console.log($("#fileChooser3")[0].files[0]);
});

Check your console output to see you get the size, type and lastModifiedDate. I think it's reasonable to assume that if all of those are the same you're dealing with the same file (barring files of 0 size).

Test it out on this fiddle

Community
  • 1
  • 1
Spork
  • 1,631
  • 1
  • 21
  • 37