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

How to Upload Files with JavaScript and Track Their Progress?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 04:38:02965browse

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();

2. Append the File to the FormData:

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

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});

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 + "%";
    }
});

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 + "%";
    }
});

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:
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