Part 1: Setting up the file upload
We can select a file and click upload. The file will be sent to the server using AJAX without refreshing the page.
- index.html — Web frontend file.
- upload.php — Backend script that handles uploads.
- uploads/ — A folder to store the uploaded files.
<h2>Upload a File</h2>
<input type="file" id="fileInput">
<button id="uploadBtn">Upload</button>
<div id="status"></div>
$('#uploadBtn').on('click', function () {
var file = $('#fileInput')[0].files[0];
if (!file) {
$('#status').text('Please select a file.');
return;
}
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
$('#status').html(response);
},
error: function () {
$('#status').text('An error occurred while uploading.');
}
});
});