0

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

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

当它应该显示文件名时,它一直显示未定义。为什么是这样?目前发生的情况是,当用户上传文件时,文件被上传到“ImageFiles”文件夹中,上传完成后,下面的 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>
4

2 回答 2

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;   
}
于 2012-04-16T12:56:59.360 回答
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;   
}
于 2012-04-16T12:57:16.170 回答