0

I'm having a moment.

                var files = document.getElementById("filePostInput").files;
            LogData("files length " + files.length); // 1
            var formData = new FormData();
            
            for (var file in files)
            {
                formData.append("file",files[file].data,files[file].name);
                LogData("file name" + files[file].name);
            }

The Output:

Thu, 26 Apr 2018 09:39:47 GMT: file nameitem

Thu, 26 Apr 2018 09:39:47 GMT: file nameundefined

Thu, 26 Apr 2018 09:39:47 GMT: file nameTest.txt

Thu, 26 Apr 2018 09:39:47 GMT: files length 1

When I call files.length, I get 1. My foreach loop however, logs 3 file name's. The first is the name of the file I put into my file input, and the next two I have no idea what they are.

Could someone explain to me what is happening here?

Thanks!

Community
  • 1
  • 1
Thomas Harris
  • 573
  • 4
  • 14

1 Answers1

2

Use for (var file of files) instead of for (var file in files). A for .. in loop iterates over all the properties of files; a for .. of loop iterates over the items in the collection. This way you don't need the [] notation either:

for (var file of files)
{
    formData.append("file", file.data , file.name);
    LogData("file name" + file.name);
}
Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
  • Thank you! I knew I had to be doing something silly. C# Habits. I can't accept your answer for nine minutes for some reason but i'll be back :) – Thomas Harris Apr 26 '18 at 10:01