Sure! Here’s a basic example of how you can implement file upload and download with a progress bar using PHP, JavaScript, and AJAX.
Create an index.html
file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload with Progress Bar</title>
<style>
#progress-bar {
width: 0;
height: 20px;
background-color: green;
}
</style>
</head>
<body>
<h2>Upload File</h2>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br><br>
<input type="submit" value="Upload">
</form>
<div id="progress-container">
<div id="progress-bar"></div>
</div>
<div id="uploadStatus"></div>
<script>
document.getElementById('uploadForm').onsubmit = function(event) {
event.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total) * 100;
document.getElementById('progress-bar').style.width = percentComplete + '%';
}
};
xhr.onload = function( ) {
if (xhr.status == 200) {
document.getElementById('uploadStatus').innerHTML = 'File uploaded successfully!';
} else {
document.getElementById('uploadStatus').innerHTML = 'File upload failed!';
}
};
xhr.send(formData);
};
</script>
</body>
</html>
Create an upload.php
file with the following content:
<?php
if ($_FILES['file']['name']) {
$filename = $_FILES['file']['name'];
$location = 'uploads/' . $filename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
echo 'File uploaded successfully!';
} else {
echo 'File upload failed!';
}
}
?>
Add the following code to your index.html
file to create a download link:
<h2>Download File</h2>
<a href="download.php?file=example.txt">Download example.txt</a>
Create a download.php
file with the following content:
<?php
if (isset($_GET['file'])) {
$file = 'uploads/' . $_GET['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found!';
}
}
?>
uploads
directory.This setup should give you a basic file upload and download system with a progress bar. If you need more advanced features or customization, you can refer to detailed tutorials like those on CodeShack1 and CodexWorld2.