FileReader: 中止事件 (abort)

在中止读取时会触发 abort 事件:例如程序调用FileReader.abort().

Bubbles No
可取消 No
接口 ProgressEvent
事件处理属性 FileReader.onabort

示例

实例

HTML

html

<div class="example">
  <div class="file-select">
    <label for="avatar">选择你的头像:</label>
    <input
      type="file"
      id="avatar"
      name="avatar"
      accept="image/png, image/jpeg" />
  </div>

  <img src="" class="preview" height="200" alt="图像预览..." />

  <div class="event-log">
    <label>事件日志:</label>
    <textarea readonly class="event-log-contents"></textarea>
  </div>
</div>

JS

js

const fileInput = document.querySelector('input[type="file"]');
const preview = document.querySelector("img.preview");
const eventLog = document.querySelector(".event-log-contents");
const reader = new FileReader();

function handleEvent(event) {
  eventLog.textContent =
    eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`;

  if (event.type === "load") {
    preview.src = reader.result;
  }
}

function addListeners(reader) {
  reader.addEventListener("loadstart", handleEvent);
  reader.addEventListener("load", handleEvent);
  reader.addEventListener("loadend", handleEvent);
  reader.addEventListener("progress", handleEvent);
  reader.addEventListener("error", handleEvent);
  reader.addEventListener("abort", handleEvent);
}

function handleSelected(e) {
  eventLog.textContent = "";
  const selectedFile = fileInput.files[0];
  if (selectedFile) {
    addListeners(reader);
    reader.readAsDataURL(selectedFile);
  }
  reader.abort();
}

fileInput.addEventListener("change", handleSelected);
返回返回发的;

结果

规范

Specification
File API
# dfn-abort-event
File API
# dfn-onabort

浏览器兼容性

BCD tables only load in the browser

参见