Home > Web Front-end > JS Tutorial > How to Upload Files with JavaScript and Track Their Progress?

How to Upload Files with JavaScript and Track Their Progress?

Linda Hamilton
Release: 2024-11-10 04:38:02
Original
1047 people have browsed it

How to Upload Files with JavaScript and Track Their Progress?

Uploading Files with JavaScript

To upload a file selected through an input element, you can use the FormData object. Here's how:

1. Create a FormData Object:

let formData = new FormData();
Copy after login

2. Append the File to the FormData:

let photo = document.getElementById("image-file").files[0];
formData.append("photo", photo);
Copy after login

3. Send the Data to the Server:

Using the fetch API, you can send the FormData to the specified URL:

fetch('/upload/image', {method: "POST", body: formData});
Copy after login

Listening for Upload Progress

To monitor the upload progress, you can use the EventTarget's addEventListener() method:

let progressBar = document.getElementById("progress-bar");

formData.addEventListener("progress", (event) => {
    if (event.lengthComputable) {
        let percentComplete = Math.round((event.loaded / event.total) * 100);
        progressBar.style.width = percentComplete + "%";
    }
});
Copy after login

Complete Code Example

Combining the file upload and progress tracking into a single example:

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

let progressBar = document.getElementById("progress-bar");

fetch('/upload/image', {method: "POST", body: formData})
.then((response) => {
    console.log(response);  // Handle server response
})
.catch((error) => {
    console.error(error);  // Handle upload failure
});

formData.addEventListener("progress", (event) => {
    if (event.lengthComputable) {
        let percentComplete = Math.round((event.loaded / event.total) * 100);
        progressBar.style.width = percentComplete + "%";
    }
});
Copy after login

This code will create a POST request to the "/upload/image" URL, send the file data, and display the upload progress using a progress bar.

The above is the detailed content of How to Upload Files with JavaScript and Track Their Progress?. For more information, please follow other related articles on the PHP Chinese website!

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