首頁  >  文章  >  web前端  >  如何使用 JavaScript 上傳檔案?

如何使用 JavaScript 上傳檔案?

DDD
DDD原創
2024-11-14 22:49:02465瀏覽

How to Upload Files With JavaScript?

How to Upload a File Using JavaScript

To upload a file using JavaScript, you can leverage the following steps:

  1. Use Form Data:

    • Create a FormData object to store the file and additional data.
    • Append the file to the form data using formData.append() .
  2. Make an XHR Request:

    • Create an XMLHttpRequest (XHR) object.
    • Set the request method to "POST" and the URL to the upload endpoint.
    • Set the body property of the XHR object to the formData .
  3. Listen for Upload Events:

    • Add event listeners to the XHR object for the load , progress , and error events.
    • In these event handlers, you can handle the upload status and response.

Example Code:

const formData = new FormData();
const fileInput = document.getElementById('image-file');
const file = fileInput.files[0];

formData.append('photo', file);

const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/image');
xhr.send(formData);

xhr.addEventListener('load', () => {
  // Handle successful upload
});

xhr.addEventListener('progress', (e) => {
  // Monitor upload progress
});

xhr.addEventListener('error', (e) => {
  // Handle upload errors
});

Pure JavaScript:

If you want to use pure JavaScript without XHR, you can use the fetch API with FormData .

Example:

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();

formData.append("photo", photo);
fetch('/upload/image', { method: "POST", body: formData });

以上是如何使用 JavaScript 上傳檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn