Hi! Today I will help you create a simple and convenient system for uploading files with progress display in JavaScript. This functionality is useful when the user needs to download large files and it is important to see how far the process has progressed.
Let's take a step-by-step look at this process, with detailed explanations of each step.
Step 1. Creating an HTML form for uploading files
First of all, we need to create a form that will allow the user to select a file to upload. In HTML, this is done using the <input> element with the file type.
HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload with Progress</title>
</head>
<body>
<h1>Загрузка файла с прогрессом</h1>
<form id="uploadForm">
<input type="file" id="fileInput" name="file" />
<button type="submit">Загрузить файл</button>
</form>
<!-- Прогресс-бар -->
<progress id="progressBar" value="0" max="100" style="width: 100%;"></progress>
<!-- Результат -->
<div id="status"></div>
<script src="script.js"></script>
</body>
</html>
📋 Explanation:
The
<input type="file">element allows the user to select a file to upload.The
<progress>progress bar displays the percentage of the file download.The
<div id="status">element will be used to display messages about the download status (success or error).
Step 2. Adding a form event handler
When the user selects a file and clicks on the "Upload" button, we need to intercept this event and transfer the file to the server. To do this, we will add a form handler and cancel its standard behavior (page reload).
Add the handler to script.js:
document.getElementById('uploadForm').addEventListener('submit', function (event) {
event.preventDefault(); // Cancel standard form behavior
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
uploadFile(file); // Passing the file to the function for loading
} else {
alert('Please select a file.');
}
});
🛑 What's going on here:
We are listening to the
submitevent on the form.Cancel the standard behavior of sending the form.
Check if the user has selected a file, and if so, call the function to load the file
uploadFile().
Step 3. Setting up file download using XMLHttpRequest
Now let's move on to the main part — uploading a file to the server with progress tracking. To do this, we will use the XMLHttpRequest object, which allows us to send files and receive information about the progress of the download.
Implementation of the uploadFile function:
function uploadFile(file) {
const xhr = new XMLHttpRequest(); // Create a new XMLHttpRequest
const formData = new FormData(); // Using FormData to send a file
formData.append('file', file); // Adding a file to the FormData object
// Handler for tracking download progress
xhr.upload.addEventListener('progress', function (event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
document.getElementById('progressBar').value = percentComplete; // Updating the progress bar
}
});
// Handler for successful download
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
document.getElementById('status').textContent = 'File uploaded successfully!';
} else {
document.getElementById('status').textContent = 'Error loading file.';
}
});
// Error handler
xhr.addEventListener('error', function () {
document.getElementById('status').textContent = 'An error occurred while uploading the file.';
});
xhr.open('POST', '/upload'); // Specify the method and URL for sending the file
xhr.send(formData); // Sending data
}
📦 Analysis of the work:
Creation
XMLHttpRequest: This object is responsible for sending HTTP requests.FormData: We useFormDatato package the file data that will be sent to the server.Tracking progress: We use the
progressevent to track the number of bytes uploaded to the server and update our progress bar.Processing download completion: If the upload is successful (status
200), we display a message about the successful upload, otherwise we show an error message.Error handling: We track the error during loading and notify the user in case of a failure.
Step 4. Setting up the server to process the file
To complete our project, you need to configure the server that will receive the file. As an example, you can use a server on Node.js using the express library and the multer package, which helps to process uploaded files.
Example of a server on Node.js:
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const upload = multer({ dest: 'uploads/' }); // Specify the folder for uploading files
// File upload path
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('File was not uploaded.');
}
res.send('File uploaded successfully!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
🌍 Explanation:
We use the
multerlibrary to process uploaded files.The server accepts the file, loads it into the specified folder (
uploads/), and returns the response to the client.
Step 5. Testing
Now that we have configured both the client and server parts, we can test the file upload. Start the server, open the page with the download form, select the file, and you will see how the progress bar will be filled as the file is downloaded.
Conclusion
Downloading a file with a progress bar is a great way to improve the user experience, especially when working with large files. The user sees how the process is progressing, which makes their interaction with the application more understandable and transparent.
If you have any questions or want to add additional features, such as support for multiple files or displaying the remaining time, let me know! 👨💻
