Home > Web Front-end > JS Tutorial > How to Transmit Files to a Server Using JavaScript?

How to Transmit Files to a Server Using JavaScript?

Mary-Kate Olsen
Release: 2024-11-15 07:51:02
Original
496 people have browsed it

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});
Copy after login

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);
  }
});
Copy after login

The above is the detailed content of How to Transmit Files to a Server Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template