Reputation: 183
Using jquery I can grab the entered filename (I just want the name, not the data) from
<form enctype="multipart/form-data">
<input type="file" id="id_myfile">
</form>
just by using
$('#id_myfile').val();
But what if I want to use the multiple attribute:
<form enctype="multipart/form-data">
<input type="file" id="id_myfile" multiple="multiple">
</form>
?
Now I get a comma-separated list containing the several filenames. Isn't there a way to use an array for the input name
<form enctype="multipart/form-data">
<input type="file" name="name_myfile[]" multiple="multiple">
</form>
and get the individual filenames into an array, to be read like this:
$('input[name="name_myfile[]"]').eq(0).val())
$('input[name="name_myfile[]"]').eq(1).val())
etc? This method does not work and results in undefined errors.
I've read here that this approach (the array name in the input, not the jquery part) works with submitted forms, several examples having been given using php and its builtin naming arrays ($_FILES, etc.). We are using classic ASP, but that's beside the point, since I'm talking client-side here. Can the filenames be put into an array in some way like I'm suggesting here to be read in JavaScript? Or, is there a completely different/better way to get a list of filenames from the user (I mean, letting the user browse, not having them type the names in, of course)?
Upvotes: 1
Views: 4503
Reputation: 522
This can be done without JQuery, check this link.
var x = document.getElementById("name_myfile");
var files = x.files; //contains all files selected
var name = files[0].name; //contains the name of the first file
The files array also contains the size in bytes of every file. To get the filename and no the full path check this one
Code copied from Link and modified to fit the sample:
if (name) {
var startIndex = (name.indexOf('\\') >= 0 ? name.lastIndexOf('\\') : name.lastIndexOf('/'));
var filename = name.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
alert(filename);
}
Upvotes: 4