FileList: item() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Note: This feature is available in Web Workers.

Phương thức item() của giao diện FileList trả về đối tượng File đại diện cho tệp tại chỉ mục được chỉ định trong danh sách tệp.

Cú pháp

js
item(index)

Tham số

index

Chỉ mục dựa trên 0 của tệp cần lấy từ danh sách.

Giá trị trả về

Đối tượng File đại diện cho tệp được yêu cầu.

Ví dụ

In tên tệp

Trong ví dụ này, chúng ta sử dụng item() để chọn mục đầu tiên trong FileList.

HTML

html
<input type="file" />
<div class="output"></div>

JavaScript

js
const fileInput = document.querySelector("input[type=file]");
const output = document.querySelector(".output");

fileInput.addEventListener("change", () => {
  const fileList = fileInput.files;
  if (fileList.length > 0) {
    const file = fileList.item(0);
    output.textContent = `You selected: ${file.name}`;
  }
});

Kết quả

Thông số kỹ thuật

Thông số kỹ thuật
File API
# dfn-item

Tương thích trình duyệt