Create a FileList and copy it to a File input

Fredrik Öberg picture Fredrik Öberg · Sep 2, 2013 · Viewed 9.3k times · Source

I'm trying to create a drag and drop area that will get dataTransfer items by webkitGetAsEntry and check if the entry is a directory or file.

I then would like to be able to make the files into a FileList and copy that to a file input (that will be validated and proccesed before posted).

JSFiddle

  function handleDrop(event) {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'copy';
        var length = event.dataTransfer.items.length;
        var elFileInput = document.getElementById('File');
        for (var i = 0; i < length; i++) {
            var entry = event.dataTransfer.items[i].webkitGetAsEntry();
            if (entry.isFile) {
                convertFilesToFileObjects(entry);          
            } 
            else if (entry.isDirectory) {
                var dirReader = entry.createReader();
                dirReader.readEntries(function(entries) {
                    for (var j = 0; j < entries.length; j++) {
                        convertFileEntrysToFileObjects(entries[j]);
                    }
                });
            }
        }   
        function convertFileEntrysToFileObjects(fileEntry) {        
            var addFileToInput = function (file) {
                console.log(file);
                //elFileInput.files = event.dataTransfer.files;
                //Need to make a FileList and populate it with Files.
            };       
            if (fileEntry.isFile) {
                fileEntry.file(function (addFileToInput, file) {
                    addFileToInput(file);
                }.bind(this, addFileToInput));
            }
        }
    }

I cannot copy a file to the FileList in the HTMLInputElement it's readonly W3 FileList Interface

I'm stuck at trying to make a FileList object by using prototypes and extending objects, I haven't quite wrapped my head around JS inheritance and prototypes yet.

I's it even possible to make a FileList object and populate it with files, then copy it to the InputElement?

Edited: Wrong JSFiddle link.

Answer

Formiga picture Formiga · Sep 3, 2013

Why do you need to copy a file to FileList?

Use FileReader instead. But validate a file before send is not a good idea. For security, you should do this in server side. You can validate the file before, but you SHOULD validate the file again when received.

https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader