Home > Web Front-end > JS Tutorial > How to Upload Files With JavaScript?

How to Upload Files With JavaScript?

DDD
Release: 2024-11-14 22:49:02
Original
523 people have browsed it

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

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

The above is the detailed content of How to Upload Files With 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template