Maison  >  Article  >  interface Web  >  Comment transmettre des fichiers à un serveur à l’aide de JavaScript ?

Comment transmettre des fichiers à un serveur à l’aide de JavaScript ?

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-11-15 07:51:02421parcourir

How to Transmit Files to a Server Using JavaScript?

File Upload with JavaScript

When a webpage allows users to select files using a file input element, the selected file's name can be retrieved from document.getElementById("image-file").value. But how do you transmit this file to a server?

For file uploads, JavaScript offers several approaches. One option is using the Fetch API:

Pure JS (Fetch)

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

This approach creates a formData object, appends the selected file to it, and uses Fetch to send the formData to the specified URL.

File Upload Status Notification

To listen for file upload completion, you can use the XMLHttpRequest object to create a FormData object and set its onreadystatechange event listener. When the file upload is complete, the event's readyState property will be 4.

// Register file input
const fileInput = document.getElementById('image-file');

// Add event listener for onreadystatechange
fileInput.addEventListener('change', (e) => {
  const files = e.target.files;
  
  if (files.length > 0) {
    // Create a FormData object
    const formData = new FormData();
    
    // Append selected files to FormData object
    for (const file of files) {
      formData.append('files', file);
    }

    // Create an XMLHttpRequest object
    const xhr = new XMLHttpRequest();

    // Open a POST request to the server
    xhr.open('POST', '/upload/image');

    // Set the onreadystatechange event listener
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          // File upload completed successfully
          console.log('File uploaded successfully!');
        } else {
          // File upload failed
          console.error('File upload failed!');
        }
      }
    };

    // Send the FormData object
    xhr.send(formData);
  }
});

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn