文件 API - reader.onload 从未被触发?

File API - reader.onload is never triggered?

我有多个文件输入,想为每个输入生成上传文件的预览。我正在等待所有这些输入的变化,然后触发 new FileReader()。不幸的是,onload 操作从未​​被触发,我做错了什么?

$("body").on("change", ".file", function(event){
  showPreview(event);
})

function showPreview(event){
 console.log("showPreview started");
  
 var file = event.target.files[0];
        console.log("file loaded: ", file);
  
        var reader = new FileReader();
        console.log("reader initiated: ", reader);
  
        reader.onload = function(event) {
     console.log("this never works : ", event);
          console.log(event.target.result);
        };
}
label {
  margin: 0 auto;
  display: block;
  width: 200px;
  height: 100px;
}

.preview {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: solid 5px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

https://jsfiddle.net/x59gctL5/

您需要通过读取实际文件来触发事件

reader.readAsDataURL(file);reader.readAsText(file);

然后就可以插入图片了:

$span.html('<img src="' + event.target.result + '" />')

或文本:

$span.html(event.target.result)

$("body").on("change", ".file", function(event) {
  showPreview(event);
})

function showPreview(event) {
  console.log("showPreview started");
  var $span = $(event.target).prev();
  var file = event.target.files[0];
  console.log("file loaded: ", file);

  var reader = new FileReader();
  console.log("reader initiated: ", reader);

  reader.onload = function(event) {
    console.log(event.target.result);
    $span.html('<img src="' + event.target.result + '" />')

  };
  reader.readAsDataURL(file);
}
label {
  margin: 0 auto;
  display: block;
  width: 200px;
  height: 100px;
}

.preview {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: solid 5px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

<label>
  <span class="preview"></span>
  <input type="file" class="file">
</label>

您需要在事件处理程序中调用 readAsText()

documentation

工作代码:

function showPreview(event){
  // ... rest of your code

  reader.onload = function(event) {
    console.log("this never works : ", event);
    console.log(event.target.result);
  };

  reader.readAsText(file);
}