admin管理员组

文章数量:1303968

İ 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?

İ 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?

Share Improve this question edited Mar 28, 2020 at 23:51 Tarek.hms asked Oct 30, 2013 at 13:33 Tarek.hmsTarek.hms 1,2831 gold badge10 silver badges15 bronze badges 4
  • try an ajax technique, using XMLHttpRequest – jamesTheProgrammer Commented Oct 30, 2013 at 13:49
  • Why the XMLHttpRequest it's not a server side – Tarek.hms Commented Oct 30, 2013 at 13:51
  • stackoverflow./questions/12530158/… – jamesTheProgrammer Commented Oct 30, 2013 at 13:52
  • That's not my question thank you anyway – Tarek.hms Commented Oct 30, 2013 at 13:54
Add a ment  | 

3 Answers 3

Reset to default 3

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.

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.

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

本文标签: formsHow to save the file input data to a variable in javascriptStack Overflow