Làm cách nào để lấy giá trị từ tệp JavaScript sang HTML?

Sử dụng API tệp, nội dung web có thể yêu cầu người dùng chọn các tệp cục bộ và sau đó đọc nội dung của các tệp đó. Lựa chọn này có thể được thực hiện bằng cách sử dụng phần tử HTML

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
4 hoặc bằng cách kéo và thả

Hãy xem xét HTML này

<input type="file" id="input" multiple />

API tệp cho phép truy cập một đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
5 chứa
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6 đại diện cho các tệp do người dùng chọn

Thuộc tính

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
7 trên phần tử
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
8 cho phép người dùng chọn nhiều tệp

Truy cập tệp được chọn đầu tiên bằng bộ chọn DOM cổ điển

const selectedFile = document.getElementById('input').files[0];

Cũng có thể (nhưng không bắt buộc) truy cập vào

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
5 thông qua sự kiện
const numFiles = fileList.length;
0. Bạn cần sử dụng
const numFiles = fileList.length;
1 để thêm trình xử lý sự kiện
const numFiles = fileList.length;
0, như thế này

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}

Đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
5 do DOM cung cấp liệt kê tất cả các tệp được người dùng chọn, mỗi tệp được chỉ định là đối tượng
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6. Bạn có thể xác định có bao nhiêu tệp mà người dùng đã chọn bằng cách kiểm tra giá trị của thuộc tính
const numFiles = fileList.length;
5 của danh sách tệp

________số 8_______

Có thể truy xuất các đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6 riêng lẻ bằng cách truy cập danh sách dưới dạng một mảng

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}

Vòng lặp này lặp qua tất cả các tệp trong danh sách tệp

Có ba thuộc tính được cung cấp bởi đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6 chứa thông tin hữu ích về tệp

const numFiles = fileList.length;
8

Tên tệp dưới dạng chuỗi chỉ đọc. Đây chỉ là tên tệp và không bao gồm bất kỳ thông tin đường dẫn nào

const numFiles = fileList.length;
9

Kích thước của tệp tính bằng byte dưới dạng số nguyên 64 bit chỉ đọc

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
0

Loại MIME của tệp dưới dạng chuỗi chỉ đọc hoặc

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
1 nếu không xác định được loại

Ví dụ sau đây cho thấy khả năng sử dụng thuộc tính

const numFiles = fileList.length;
9

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>

Bạn có thể ẩn phần tử

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
3 tệp xấu xí được thừa nhận và hiển thị giao diện của riêng bạn để mở bộ chọn tệp và hiển thị tệp hoặc tệp mà người dùng đã chọn. Bạn có thể thực hiện việc này bằng cách tạo kiểu cho phần tử đầu vào bằng
for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
4 và gọi phương thức
for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
5 trên phần tử
for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
3

Hãy xem xét HTML này

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>

Mã xử lý sự kiện

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
7 có thể trông như thế này

const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);

Bạn có thể tạo kiểu cho

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
8 theo cách bạn muốn

Để cho phép mở bộ chọn tệp mà không cần sử dụng JavaScript (phương thức click()), có thể sử dụng phần tử

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
9. Lưu ý rằng trong trường hợp này, không được ẩn phần tử đầu vào bằng cách sử dụng
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
0 (hoặc
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
1), nếu không, nhãn sẽ không thể truy cập được bằng bàn phím. Thay vào đó, hãy sử dụng kỹ thuật ẩn trực quan

Hãy xem xét HTML này

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  class="visually-hidden" />
<label for="fileElem">Select some files</label>

và CSS này

.visually-hidden {
  position: absolute !important;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px, 1px, 1px, 1px);
}

input.visually-hidden:is(:focus, :focus-within) + label {
  outline: thin dotted;
}

Không cần thêm mã JavaScript để gọi

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
2. Ngoài ra, trong trường hợp này, bạn có thể tạo kiểu cho thành phần nhãn theo ý muốn. Bạn cần cung cấp một gợi ý trực quan về trạng thái tiêu điểm của trường nhập ẩn trên nhãn của nó, có thể là đường viền như minh họa ở trên hoặc màu nền hoặc bóng hộp. (Tại thời điểm viết bài này, Firefox không hiển thị gợi ý trực quan này cho các phần tử
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
3. )

Bạn cũng có thể cho phép người dùng kéo và thả tệp vào ứng dụng web của mình

Bước đầu tiên là thiết lập một khu vực thả. Chính xác phần nào trong nội dung của bạn sẽ chấp nhận sự sụt giảm có thể khác nhau tùy thuộc vào thiết kế của ứng dụng của bạn, nhưng việc tạo một phần tử nhận sự kiện giảm là dễ dàng

const selectedFile = document.getElementById('input').files[0];
0

Trong ví dụ này, chúng tôi đang chuyển phần tử có ID

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
4 vào vùng thả của chúng tôi. Điều này được thực hiện bằng cách thêm người nghe cho các sự kiện
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
5,
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
6 và
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
7

Chúng tôi thực sự không cần phải làm bất cứ điều gì với các sự kiện

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
5 và
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
      const uploadInput = document.getElementById("uploadInput");
      uploadInput.addEventListener(
        "change",
        () => {
          // Calculate total size
          let numberOfBytes = 0;
          for (const file of uploadInput.files) {
            numberOfBytes += file.size;
          }

          // Approximate to the closest prefixed unit
          const units = [
            "B",
            "KiB",
            "MiB",
            "GiB",
            "TiB",
            "PiB",
            "EiB",
            "ZiB",
            "YiB",
          ];
          const exponent = Math.min(
            Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
            units.length - 1
          );
          const approx = numberOfBytes / 1024 ** exponent;
          const output =
            exponent === 0
              ? `${numberOfBytes} bytes`
              : `${approx.toFixed(3)} ${
                  units[exponent]
                } (${numberOfBytes} bytes)`;

          document.getElementById("fileNum").textContent = uploadInput.files.length;
          document.getElementById("fileSize").textContent = output;
        },
        false
      );
    </script>
  </body>
</html>
6 trong trường hợp của chúng tôi, vì vậy cả hai chức năng này đều đơn giản. Họ chỉ dừng truyền bá sự kiện và ngăn hành động mặc định xảy ra

const selectedFile = document.getElementById('input').files[0];
1

Điều kỳ diệu thực sự xảy ra trong hàm

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
0

const selectedFile = document.getElementById('input').files[0];
2

Ở đây, chúng tôi truy xuất trường

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
1 từ sự kiện, kéo danh sách tệp ra khỏi đó rồi chuyển trường đó tới
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
2. Kể từ thời điểm này, việc xử lý các tệp là như nhau cho dù người dùng sử dụng phần tử
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
8 hay kéo và thả

Giả sử bạn đang phát triển trang web chia sẻ ảnh tuyệt vời tiếp theo và muốn sử dụng HTML để hiển thị bản xem trước hình thu nhỏ của hình ảnh trước khi người dùng thực sự tải chúng lên. Bạn có thể thiết lập phần tử đầu vào hoặc vùng thả của mình như đã thảo luận trước đó và yêu cầu họ gọi một hàm, chẳng hạn như hàm

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
2 bên dưới

const selectedFile = document.getElementById('input').files[0];
3

Ở đây, vòng lặp của chúng tôi xử lý các tệp do người dùng chọn sẽ xem xét thuộc tính

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
0 của từng tệp để xem liệu loại MIME của nó có bắt đầu bằng chuỗi "
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
6"). Đối với mỗi tệp là một hình ảnh, chúng tôi tạo một phần tử
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
7 mới. CSS có thể được sử dụng để thiết lập bất kỳ đường viền hoặc bóng đẹp nào và để chỉ định kích thước của hình ảnh, do đó không cần phải thực hiện ở đây

Mỗi hình ảnh có lớp CSS

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
8 được thêm vào, giúp dễ dàng tìm thấy trong cây DOM. Chúng tôi cũng thêm thuộc tính
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
9 vào mỗi hình ảnh chỉ định
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6 cho hình ảnh; . Chúng tôi sử dụng
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
1 để thêm hình thu nhỏ mới vào khu vực xem trước của tài liệu của chúng tôi

Tiếp theo, chúng tôi thiết lập

const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
2 để xử lý tải hình ảnh không đồng bộ và gắn nó vào phần tử
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
7. Sau khi tạo đối tượng
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
2 mới, chúng tôi thiết lập chức năng
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
5 của nó và sau đó gọi
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
6 để bắt đầu thao tác đọc trong nền. Khi toàn bộ nội dung của tệp hình ảnh được tải, chúng được chuyển đổi thành một URL
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
7 được chuyển đến lệnh gọi lại
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", (e) => {
  if (fileElem) {
    fileElem.click();
  }
}, false);
5. Việc triển khai quy trình này của chúng tôi đặt thuộc tính
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  class="visually-hidden" />
<label for="fileElem">Select some files</label>
0 của phần tử
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
7 cho hình ảnh được tải, dẫn đến hình ảnh xuất hiện trong hình thu nhỏ trên màn hình của người dùng

Các phương thức DOM

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  class="visually-hidden" />
<label for="fileElem">Select some files</label>
1 và
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  class="visually-hidden" />
<label for="fileElem">Select some files</label>
2 cho phép bạn tạo các chuỗi URL đơn giản có thể được sử dụng để tham chiếu bất kỳ dữ liệu nào có thể được tham chiếu bằng cách sử dụng đối tượng DOM
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6, bao gồm các tệp cục bộ trên máy tính của người dùng

Khi bạn có một đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6 mà bạn muốn tham chiếu bằng URL từ HTML, bạn có thể tạo một URL đối tượng cho nó như thế này

const selectedFile = document.getElementById('input').files[0];
4

URL đối tượng là một chuỗi xác định đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6. Mỗi khi bạn gọi
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  class="visually-hidden" />
<label for="fileElem">Select some files</label>
1, một URL đối tượng duy nhất sẽ được tạo ngay cả khi bạn đã tạo một URL đối tượng cho tệp đó rồi. Mỗi trong số này phải được phát hành. Mặc dù chúng được giải phóng tự động khi tài liệu được tải xuống, nhưng nếu trang của bạn sử dụng chúng một cách linh hoạt, bạn nên giải phóng chúng một cách rõ ràng bằng cách gọi
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  class="visually-hidden" />
<label for="fileElem">Select some files</label>
2

const selectedFile = document.getElementById('input').files[0];
5

Ví dụ này sử dụng URL đối tượng để hiển thị hình thu nhỏ của hình ảnh. Ngoài ra, nó còn hiển thị thông tin tệp khác bao gồm tên và kích thước của chúng

HTML trình bày giao diện trông như thế này

const selectedFile = document.getElementById('input').files[0];
6

Điều này thiết lập phần tử tệp

for (let i = 0, numFiles = fileList.length; i < numFiles; i++) {
  const file = fileList[i];
  // …
}
3 của chúng tôi cũng như một liên kết gọi bộ chọn tệp (vì chúng tôi ẩn đầu vào tệp để ngăn giao diện người dùng kém hấp dẫn đó hiển thị). Điều này được giải thích trong phần, cũng như phương thức gọi bộ chọn tệp

Phương pháp

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
2 sau đây

const selectedFile = document.getElementById('input').files[0];
7

Điều này bắt đầu bằng cách tìm nạp URL của

.visually-hidden {
  position: absolute !important;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px, 1px, 1px, 1px);
}

input.visually-hidden:is(:focus, :focus-within) + label {
  outline: thin dotted;
}
0 với ID
.visually-hidden {
  position: absolute !important;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px, 1px, 1px, 1px);
}

input.visually-hidden:is(:focus, :focus-within) + label {
  outline: thin dotted;
}
1. Đây là khối mà chúng tôi sẽ chèn danh sách tệp của mình, bao gồm cả hình thu nhỏ

Nếu đối tượng

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
5 được chuyển đến
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
2 là
.visually-hidden {
  position: absolute !important;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px, 1px, 1px, 1px);
}

input.visually-hidden:is(:focus, :focus-within) + label {
  outline: thin dotted;
}
4, chúng tôi đặt HTML bên trong của khối để hiển thị "Không có tệp nào được chọn. ". Mặt khác, chúng tôi bắt đầu xây dựng danh sách tệp của mình, như sau

  1. Một phần tử danh sách không có thứ tự mới (
    .visually-hidden {
      position: absolute !important;
      height: 1px;
      width: 1px;
      overflow: hidden;
      clip: rect(1px, 1px, 1px, 1px);
    }
    
    input.visually-hidden:is(:focus, :focus-within) + label {
      outline: thin dotted;
    }
    
    5) được tạo
  2. Phần tử danh sách mới được chèn vào khối
    .visually-hidden {
      position: absolute !important;
      height: 1px;
      width: 1px;
      overflow: hidden;
      clip: rect(1px, 1px, 1px, 1px);
    }
    
    input.visually-hidden:is(:focus, :focus-within) + label {
      outline: thin dotted;
    }
    
    0 bằng cách gọi phương thức
    const fileSelect = document.getElementById("fileSelect");
    const fileElem = document.getElementById("fileElem");
    
    fileSelect.addEventListener("click", (e) => {
      if (fileElem) {
        fileElem.click();
      }
    }, false);
    
    1 của nó
  3. Đối với mỗi
    const inputElement = document.getElementById("input");
    inputElement.addEventListener("change", handleFiles, false);
    function handleFiles() {
      const fileList = this.files; /* now you can work with the file list */
    }
    
    6 trong
    const inputElement = document.getElementById("input");
    inputElement.addEventListener("change", handleFiles, false);
    function handleFiles() {
      const fileList = this.files; /* now you can work with the file list */
    }
    
    5 được đại diện bởi
    const selectedFile = document.getElementById('input').files[0];
    
    00
    1. Tạo một phần tử danh sách mới (
      const selectedFile = document.getElementById('input').files[0];
      
      01) và chèn nó vào danh sách
    2. Tạo phần tử hình ảnh mới (
      const selectedFile = document.getElementById('input').files[0];
      
      02)
    3. Đặt nguồn của hình ảnh thành URL đối tượng mới đại diện cho tệp, sử dụng
      <input
        type="file"
        id="fileElem"
        multiple
        accept="image/*"
        class="visually-hidden" />
      <label for="fileElem">Select some files</label>
      
      1 để tạo URL blob
    4. Đặt chiều cao của hình ảnh thành 60 pixel
    5. Thiết lập trình xử lý sự kiện tải của hình ảnh để giải phóng URL đối tượng vì nó không còn cần thiết sau khi hình ảnh đã được tải. Điều này được thực hiện bằng cách gọi phương thức
      <input
        type="file"
        id="fileElem"
        multiple
        accept="image/*"
        class="visually-hidden" />
      <label for="fileElem">Select some files</label>
      
      2 và chuyển vào chuỗi URL đối tượng như được chỉ định bởi
      const selectedFile = document.getElementById('input').files[0];
      
      05
    6. Nối mục danh sách mới vào danh sách

Đây là bản demo trực tiếp của đoạn mã trên

Một điều khác bạn có thể muốn làm là cho phép người dùng tải tệp hoặc tệp đã chọn (chẳng hạn như hình ảnh được chọn bằng ví dụ trước) lên máy chủ. Điều này có thể được thực hiện không đồng bộ rất dễ dàng

Tiếp tục với đoạn mã đã tạo hình thu nhỏ trong ví dụ trước, hãy nhớ lại rằng mọi hình ảnh thu nhỏ đều thuộc lớp CSS

<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
8 với
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
6 tương ứng được đính kèm trong thuộc tính
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
9. Điều này cho phép chúng tôi chọn tất cả các hình ảnh mà người dùng đã chọn để tải lên bằng cách sử dụng
const selectedFile = document.getElementById('input').files[0];
09, như thế này

const selectedFile = document.getElementById('input').files[0];
8

Dòng 2 tìm nạp một

const selectedFile = document.getElementById('input').files[0];
10, được gọi là
const selectedFile = document.getElementById('input').files[0];
11, của tất cả các thành phần trong tài liệu với lớp CSS
<input
  type="file"
  id="fileElem"
  multiple
  accept="image/*"
  style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
8. Trong trường hợp của chúng tôi, đây sẽ là tất cả các hình thu nhỏ của hình ảnh. Khi chúng ta có danh sách đó, việc lướt qua nó và tạo một phiên bản
const selectedFile = document.getElementById('input').files[0];
13 mới cho mỗi. Mỗi trong số này xử lý tải lên tệp tương ứng

Hàm

const selectedFile = document.getElementById('input').files[0];
13 chấp nhận hai đầu vào. một phần tử hình ảnh và một tệp để đọc dữ liệu hình ảnh

const selectedFile = document.getElementById('input').files[0];
9

Hàm

const selectedFile = document.getElementById('input').files[0];
15 được hiển thị ở trên tạo ra một throbber, được sử dụng để hiển thị thông tin về tiến độ, sau đó tạo một
const selectedFile = document.getElementById('input').files[0];
16 để xử lý việc tải dữ liệu lên

Trước khi thực sự chuyển dữ liệu, một số bước chuẩn bị được thực hiện

  1. Trình nghe tải lên của
    const selectedFile = document.getElementById('input').files[0];
    
    18 của ________6____18 được đặt để cập nhật thông tin phần trăm mới cho thiết bị ghi hình để khi quá trình tải lên tiến triển, thiết bị ghi hình sẽ được cập nhật dựa trên thông tin mới nhất
  2. Trình xử lý sự kiện tải lên của
    const selectedFile = document.getElementById('input').files[0];
    
    16
    const selectedFile = document.getElementById('input').files[0];
    
    20 được thiết lập để cập nhật thông tin tiến độ nhanh lên 100% nhằm đảm bảo chỉ báo tiến độ thực sự đạt 100% (trong trường hợp có vấn đề về mức độ chi tiết trong quá trình này). Sau đó, nó loại bỏ cái đập vì nó không còn cần thiết nữa. Điều này làm cho rung động biến mất sau khi quá trình tải lên hoàn tất
  3. Yêu cầu tải lên tệp hình ảnh được mở bằng cách gọi phương thức
    const selectedFile = document.getElementById('input').files[0];
    
    22 của
    const selectedFile = document.getElementById('input').files[0];
    
    16 để bắt đầu tạo yêu cầu POST
  4. Loại MIME để tải lên được đặt bằng cách gọi hàm
    const selectedFile = document.getElementById('input').files[0];
    
    16
    const selectedFile = document.getElementById('input').files[0];
    
    24. Trong trường hợp này, chúng tôi đang sử dụng loại MIME chung;
  5. Đối tượng
    const fileSelect = document.getElementById("fileSelect");
    const fileElem = document.getElementById("fileElem");
    
    fileSelect.addEventListener("click", (e) => {
      if (fileElem) {
        fileElem.click();
      }
    }, false);
    
    2 được sử dụng để chuyển đổi tệp thành chuỗi nhị phân
  6. Cuối cùng, khi nội dung được tải, hàm
    const selectedFile = document.getElementById('input').files[0];
    
    16
    const selectedFile = document.getElementById('input').files[0];
    
    27 được gọi để tải nội dung của tệp lên

Ví dụ này, sử dụng PHP ở phía máy chủ và JavaScript ở phía máy khách, minh họa việc tải tệp lên không đồng bộ

const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /* now you can work with the file list */
}
0

URL đối tượng có thể được sử dụng cho những thứ khác ngoài hình ảnh. Chúng có thể được sử dụng để hiển thị các tệp PDF được nhúng hoặc bất kỳ tài nguyên nào khác mà trình duyệt có thể hiển thị

Làm cách nào để lấy dữ liệu từ tệp JavaScript sang HTML?

Để bao gồm một tệp JavaScript bên ngoài, chúng ta có thể sử dụng thẻ script với thuộc tính src . Bạn đã sử dụng thuộc tính src khi sử dụng hình ảnh. Giá trị cho thuộc tính src phải là đường dẫn đến tệp JavaScript của bạn. Thẻ tập lệnh này phải được bao gồm giữa các thẻ

Làm cách nào để gọi hàm JavaScript trong HTML?

Để đưa tệp JavaScript của chúng ta vào tài liệu HTML, chúng ta phải sử dụng thẻ script