How to save the file input data to a variable in javascript

10,017

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
10,017
Tarek.hms
Author by

Tarek.hms

Updated on June 13, 2022

Comments

  • Tarek.hms
    Tarek.hms almost 2 years

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

  • Tarek.hms
    Tarek.hms over 10 years
    The connection still!!
  • Tarek.hms
    Tarek.hms over 10 years
    No I want the whole file, anyway this method are working fine and the connection gone as well, thank you