它一直显示未定义的文件名

时间:2012-04-16 12:49:58

标签: javascript jquery

我试图在用户上传文件后显示该文件的名称。文件上传成功,但在javascript中它会一直显示以下信息:

  

文件(未定义)已成功上传!

它应该在显示文件名时显示未定义。为什么是这样?目前正在发生的事情是用户上传文件,文件被上传到“ImageFiles”文件夹,当上传时finsihed下面的javascript函数显示消息,说明已成功上传的文件的名称。

以下是上传后显示文件名和信息的代码:

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;   
}

以下是表格:

  <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> 
    </form>

2 个答案:

答案 0 :(得分:2)

试试这个:

var fileName;
function stopImageUpload(success){

    function handleFileSelect(evt) {
    var files = evt.target.files;
    fileName = 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 ('+fileName+') was uploaded successfully!</span><br/><br/>';
    fileName = ""; //remove the temporary variable

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

      return true;   
}

答案 1 :(得分:1)

未经测试,但尝试使用getItem / setItem,看看是否有任何改变!

function stopImageUpload(success){

    function handleFileSelect(evt) {
       var files = evt.target.files;
       console.log(files[0].name); //see if a name really exists, or if something is wrong outside this function?
       localStorage.setItem("fname", files[0].name); //save the name for future use
    }

    $('.fileImage').on('change', handleFileSelect);

    var result = '';
    if (success == 1){
        result = '<span class="msg">The file ('+localStorage.getItem("fname")+') was uploaded successfully!</span><br/><br/>';
        localStorage.setItem("fname", ""); //remove the temporary variable
    } else {
        result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
    }
    return true;   
}