XMLHttpRequestUpload

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

注意:此功能在 Web Workers 中可用,但 Service Workers 除外。

XMLHttpRequestUpload 介面代表了特定 XMLHttpRequest 的上傳過程。它是一個不透明物件,代表了底層、依賴於瀏覽器的上傳過程。它是一個 XMLHttpRequestEventTarget,可以透過呼叫 XMLHttpRequest.upload 獲取。

EventTarget XMLHttpRequestEventTarget XMLHttpRequestUpload

例項屬性

此介面沒有特定的屬性,但繼承了 XMLHttpRequestEventTargetEventTarget 的屬性。

例項方法

此介面沒有特定的方法,但繼承了 XMLHttpRequestEventTargetEventTarget 的方法。

事件

此介面沒有特定的事件,但繼承了 XMLHttpRequestEventTarget 的事件。

示例

使用超時上傳檔案

這允許您將檔案上傳到伺服器;它在上傳過程中顯示一個進度條,以及一條包含進度和結果(成功或失敗)的訊息。一箇中止按鈕允許停止上傳。

HTML

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>XMLHttpRequestUpload test</title>
    <link rel="stylesheet" href="xhrupload_test.css" />
    <script src="xhrupload_test.js"></script>
  </head>
  <body>
    <main>
      <h1>Upload a file</h1>
      <p>
        <label for="file">File to upload</label><input type="file" id="file" />
      </p>
      <p>
        <progress></progress>
      </p>
      <p>
        <output></output>
      </p>
      <p>
        <button disabled id="abort">Abort</button>
      </p>
    </main>
  </body>
</html>

CSS

css
body {
  background-color: lightblue;
}

main {
  margin: 50px auto;
  text-align: center;
}

#file {
  display: none;
}

label[for="file"] {
  background-color: lightgrey;
  padding: 10px;
}

progress {
  display: none;
}

progress.visible {
  display: inline;
}

JavaScript

js
const fileInput = document.getElementById("file");
const progressBar = document.querySelector("progress");
const log = document.querySelector("output");
const abortButton = document.getElementById("abort");

fileInput.addEventListener("change", () => {
  const xhr = new XMLHttpRequest();
  xhr.timeout = 2000; // 2 seconds

  // Link abort button
  abortButton.addEventListener(
    "click",
    () => {
      xhr.abort();
    },
    { once: true },
  );

  // When the upload starts, we display the progress bar
  xhr.upload.addEventListener("loadstart", (event) => {
    progressBar.classList.add("visible");
    progressBar.value = 0;
    progressBar.max = event.total;
    log.textContent = "Uploading (0%)…";
    abortButton.disabled = false;
  });

  // Each time a progress event is received, we update the bar
  xhr.upload.addEventListener("progress", (event) => {
    progressBar.value = event.loaded;
    log.textContent = `Uploading (${(
      (event.loaded / event.total) *
      100
    ).toFixed(2)}%)…`;
  });

  // When the upload is finished, we hide the progress bar.
  xhr.upload.addEventListener("loadend", (event) => {
    progressBar.classList.remove("visible");
    if (event.loaded !== 0) {
      log.textContent = "Upload finished.";
    }
    abortButton.disabled = true;
  });

  // In case of an error, an abort, or a timeout, we hide the progress bar
  // Note that these events can be listened to on the xhr object too
  function errorAction(event) {
    progressBar.classList.remove("visible");
    log.textContent = `Upload failed: ${event.type}`;
  }
  xhr.upload.addEventListener("error", errorAction);
  xhr.upload.addEventListener("abort", errorAction);
  xhr.upload.addEventListener("timeout", errorAction);

  // Build the payload
  const fileData = new FormData();
  fileData.append("file", fileInput.files[0]);

  // Theoretically, event listeners could be set after the open() call
  // but browsers are buggy here
  xhr.open("POST", "upload_test.php", true);

  // Note that the event listener must be set before sending (as it is a preflighted request)
  xhr.send(fileData);
});

規範

規範
XMLHttpRequest
# xmlhttprequestupload

瀏覽器相容性

另見