简体   繁体   中英

I keep getting undefined below

I trying to display the name of the file after the user has uploaded it. The file uploads successfully but in the javascript it keeps appending in the list 'undefined'. Why does it keep displaying 'undefined' and not the name of the file uploaded from the file input??:

Below is the code which displays the file name and message after uploading:

function stopImageUpload(success){

    function handleFileSelect(evt) {
    var files = evt.target.files;
    localStorage["fname"] = files[0].name; //save the name for future use
}

$('.fileImage').bind('change', handleFileSelect, false);


      var result = '';
      if (success == 1){
  result = '<span class="msg">The file ('+localStorage["fname"]+') was uploaded successfully!</span><br/><br/>';
    localStorage["fname"] = undefined; //remove the temporary variable

      }
      else {
         result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
      }

      return true;   
}

Below is form:

  <form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
    <p>Image File: <input name='fileImage' type='file' class='fileImage' />
    <input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
    </p> 
    <ul class='list'></ul>
    </form>

Try breaking apart your functions. Bind the change event outside of the function that handles the form submit.

$(document).ready(function(){
    $('.fileImage').bind('change', handleFileSelect, false);
});

function handleFileSelect(evt) {
    var files = evt.target.files;
    localStorage["fname"] = files[0].name; //save the name for future use
}
function stopImageUpload(success){
      var result = '';
      if (success == 1){
  result = '<span class="msg">The file ('+localStorage["fname"]+') was uploaded successfully!</span><br/><br/>';
    localStorage["fname"] = undefined; //remove the temporary variable

      }
      else {
         result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
      }

      return true;   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM