Reputation: 385
I have a form where users can upload files. I need the program to check if the file is a PRN and, if so, if it contains the correct docket number and date in the name of the file. The problem is that a user can upload multiple files at a time. I have written a JavaScript function to check the filename before the user proceeds, but how do I deal with multiple files in JavaScript?
I have written the function to check the filename, but am at a loss as to how to proceed from here for multiple files. I am fairly new to JavaScript.
function checkFilenames(val) {
let filepath = val.value;
let n = filepath.lastIndexOf('\\');
let filename = filepath.substring(n + 1);
let d;
if (filename.contains('.prn') || filename.contains('.PRN')) {
let docketnum = <?php echo $job['docketno']; ?>;
d = new Date(<?php echo $job['hearing']; ?>*1000).toString();
let test = d.split(' ');
let month = test[1];
let monthsArray = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let numMonth;
for (let i = 0; i < 12; i++) {
if (monthsArray[i] == month) {
numMonth = (i + 1).toString();
if (numMonth.length < 2) {
numMonth = '0' + numMonth;
}
}
}
let day = test[2].toString();
if (day.length < 2) {
day = '0' + day;
}
let year = test[3];
let dateToCheck = numMonth + '-' + day + '-' + year;
if (!(filename.contains(dateToCheck) && filename.contains(docketnum))) {
alert('Please check the file');
}
}
}
When I check the filenames using alert or console.log, it just shows the first file. Is there a way around this? Would it be better to call a PHP function?
Upvotes: 0
Views: 135
Reputation: 3431
I think you best go with the DOM File API here. It allows you to access the file(s) that the user has currently selected in an <input type="file">
field.
The files
property of the field is a FileList, that you can loop over like an array. The individual File
objects in this list offer access to the name, size and type of the file directly. (Reading the actual file content would also be possible using a FileReader, but that goes beyond the scope of what you need here.)
More information on how to use this can be found for example on MDN, https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
Upvotes: 1