I want to know how does the code below work to do because I have found this on a website for getting a file’s name but I don’t fully understand how it works:
function handleFileSelect(evt) {
var files = evt.target.files;
localStorage["fname"] = files[0].name; //save the name for future use
}
Is the code above correct for a form code like below:
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >
<p><input name='fileImage' type='file' class='fileImage' /></p>
<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>
That function is bound is probably bound the to the
changeevent of that file input field.So lets break this down.
When a function is bound as a listener to an event, typically an object that represents that event is passed in. This is the
evtvariable being accepted by this event handler function.For DOM events, event objects typically have a property called
targetthat is a reference to the DOM element that triggered the event. Soevt.targetreturns the file input element.And file input elements have a property called
files, that is an array of file objects that the user has chosen (note that there may be only one file chosen, but it’s still going to be an array with only one item). That line assigns that array to thefileslocal variable.localStorageis a persistent key value store (sorta like cookies) introduced as part of HTML5."fname"is the key we are storing a value under. Andfiles[0].namegets the first file object, and returns itsnameproperty, effectively getting the name of the selected file. This value is then stored, so that even if you refresh the page you can read back that last chosen filename just by runninglocalStorage["fname"]