无法使用File Reader Javascript访问文件名

时间:2019-06-28 01:56:23

标签: javascript javascript-objects filereader

我正在制作一个浏览器中的图像预览器。图像预览加载正常,但此行上的文件名重复第一个文件名:

<div.innerHTML = "<img class='thumbnail' src='" + picfile.result + "'" +
"title='" + file.name + "'/>

我尝试了

picfile.name 
file.name 
file[i].name 
files.name 
files[i].name 

,没有一个有效。它要么输出未定义,要么破坏整个脚本。

这是文件阅读器的完整代码。

window.onload = function() {
  if (window.File && window.FileList && window.FileReader) {
    var filesInput = document.getElementById("uploadimage ");
    filesInput.addEventListener("change ", function(event) {
      var files = event.target.files;
      var output = document.getElementById("result ");
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (!file.type.match('image'))
          continue;
        var picreader = new FileReader();
        picreader.addEventListener("load ", function(event) {
          var picfile = event.target;
          var div = document.createElement("div ");
          div.innerHTML = "<img class='thumbnail' src='" + picfile.result + "' " +
            "title='" + file.name + "' /><br>";
          //div.innerHTML += picfile.name + '<br><span style="color:red">' + picfile.name.toLowerCase().replace(/[^\w\d\.]/gi, '') + '</span>';
          //filename output.insertBefore(div, null);
        });
        picreader.readAsDataURL(file);
      }
    });
  }
}
<input type="file" multiple id="uploadimage" class="file_input ">
<div id="result" class="uploadPreview "></div>

1 个答案:

答案 0 :(得分:2)

您需要在for循环中将var file = files[i];更改为let file = files[i];

有关循环内JavaScript闭合的更多参考  

JavaScript closure inside loops – simple practical example

window.onload = function() {
  if (window.File && window.FileList && window.FileReader) {
    var filesInput = document.getElementById("uploadimage");
    filesInput.addEventListener("change", function(event) {
      var files = event.target.files;
      var output = document.getElementById("result");
      for (var i = 0; i < files.length; i++) {
        let file = files[i];
        if (!file.type.match('image'))
          continue;
        var picreader = new FileReader();
        picreader.addEventListener("load", function(event) {
          var picfile = event.target;
          var div = document.createElement("div");
          console.log(file.name);
          div.innerHTML = "<img class='thumbnail' src='" + picfile.result + "'" +
            "title='" + file.name + "'/><br>";
//div.innerHTML += picfile.name+'<br><span style="color:red">'+picfile.name.toLowerCase().replace(/[^\w\d\.]/gi, '')+'</span>'; //filename
          output.insertBefore(div, null);
        });        
        picreader.readAsDataURL(file);
      } 

    });
  }
}
<input type="file" multiple id="uploadimage" class="file_input">
<div id="result" class="uploadPreview"></div>
    <script>    
  
</script>