0

I am working with an application that provides the possibility for the user to upload certain files on the server. And that works fine. But now i want to check the file endings via JavaScript to make sure that the user can only upload files of a certain format. For example: *.txt

Therefore i want to read the filename and check the ending. My problem is, that i don't know how to access the filename. I know that its quite simple to get the value of string via: document.getElementById('Field').value -> this works for me.

But how can i access the filename of a file? Do i need to transform them into files with something like fileReader? Isn't there an easier way to just get the filename.

Update: HTML5-solutions won't work for me. Isn't there an other way to do that without File-API?

dan_k
  • 33
  • 1
  • 6
  • What do you mean when you say _"I get the uploaded files as js-objects"_? Typically Javascript runs in the browser before any uploading happens. Are you using Node.js? Have you tried using `document.getElementById('input_type_file').value` to get the filename? – asontu Jan 21 '15 at 15:48
  • youre right, i deleted this sentence :-) document.getElementById('input_type_file').value doesn't work. Could this really work? I unterstand that it works with a string, then it just returns the string. But should it return the filename as value, if its a file? – dan_k Jan 21 '15 at 16:43

2 Answers2

2

There are two ways to go about it.

You can check the input value as you've already pointed out, or if your browser supports the HTML5 File API then you can use this to determine the filename.

document.getElementById('file').addEventListener('change', function(e) {
    console.log(e.target.files[0].name); //myFile.txt
});

Using this method you can even go as far as determining the MIME type to check the content type.

document.getElementById('file').addEventListener('change', function(e) {
    var type = e.target.files[0].type;
    if(type === 'text/plain') //File contains plain text
});
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
-5

Use File API to access file details.

// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
var fileInput = document.getElementById("myfileinput");

// files is a FileList object (simliar to NodeList)
var files = fileInput.files;

for (var i = 0; i < files.length; i++) {
  alert("Filename " + files[i].name);
}
dnemoga
  • 214
  • 3
  • 5