2

İ tried to do it simply by assign the files of the input into a variable:

 var files = document.getElementById("upload").files;

but there seems to be a connection created with this assign so every time the input changes the variable changes too. so how can I do that without this connection?

4

3 回答 3

2

You just want the filenames? Then just get the filenames :

var files = [],
    upload = document.getElementById("upload");

upload.onchange = function() {
    for (var i=0;i<upload.files.length;i++) {
        files.push(upload.files[i].fileName);
    }
}

??? No "inherited" behaviour from FileList, but I assume I misunderstand.

于 2013-10-30T13:58:03.933 回答
1

That's because it's being used as a reference to the files property. If you don't know what that means, do some reading on Google for "pass by value vs pass by reference."

What you need to do to copy the value unfortunately is something like this:

var files = (function() { return document.getElementById("upload").files; })();

In order to copy the value with no reference to the .files property.

The simplistic answer of what is happening here is that var files references the memory address of the files property of that DOM element. It looks to you like it's copying the value when in fact it is pointing to that memory slot and access it is just following a trail to whatever is stored there and accessing it.

于 2013-10-30T13:44:15.070 回答
1

I have modified @Mike's answer and came to a result where it actually works. I am writing the answer for a single file which can be converted to support multiple files.

var file = document.getElementById("upload").files[0]

this will store the file and not the refrence to the file hence if the value of upload file type changes the value in file remains unchanged.

Hope this might help someone else

于 2016-05-18T08:15:20.463 回答