Cloning a FileList object in JavaScript to upload files?

Ok, here is my situation. I have a JavaScript class that processes AJAX form submissions and other related synchronous and asynchronous requests. It collects the data, then sets this data into temporary storage for the request and then makes a request with the temporary storage data.

For instance:

  • The user begins to create a request, puts NAME and LAST NAME on the form
  • This data is placed in a SUBMITDATA object variable
  • When a request is made, this data is cloned to another TEMPSUBMITDATA variable
  • Once the request is complete, the data that was used to execute the request is still available (for debugging or other purposes).

This means that if two requests are simultaneously executed through the same object, I can access the data that was used to execute these requests.

Everything works as expected, until I want to use HTML5 FileList and FormData. Although I can clone objects in JavaScript with relative ease, I cannot clone a FileList. Here is an example:

<html>
<head>
    <script type="text/javascript">
        // This method is used to clone data objects
        function clone(object){
            if(object==null || typeof(object)!=='object'){
                return object;
            }
            // This line throws the error when FileList data is attempted to be cloned
            var tmp=object.constructor();
            for(var key in object){
                tmp[key]=clone(object[key]);
            }
            return tmp;
        }

        // This is an example data storage
        var submitData=new Object();
        submitData['some-data']='abc';

        function uploader(files){

            submitData['my-files']=files;

            // This clones the object and leads to the error because of FileList
            var tempSubmitData=clone(submitData);

            // HERE WOULD THE ACTUAL FORM SUBMIT HAPPEN
            // THIS EXAMPLE IS SHOWN FOR EASIER READING OF
            // THE PROBLEM EXPLAINED ABOVE

        }
    </script>
</head>
<body>
    <input type="file" name="myfile" value="" onchange="uploader(this.files);"/>
</body>

This leads me to my question: can I - in general - clone this data type in any way so that I can store it until the request is complete? Or is this the only way to make a new object every time?

, , , , - , HTMLLListList FormData.

!

+5
1

jQuery, extend , .

var clonedObject = $.extend(true,{},yourObject);

, , Object.create()

var clonedObject = Object.create(yourObject);

( , ), .

+1

All Articles