PHP Chunk File Upload using JavaScript
Chunk file upload is a technique used to break large files into smaller chunks and upload them sequentially. This approach is particularly useful when dealing with large file uploads, as it helps to overcome limitations imposed by web servers or browsers. In this article, we will explore how to implement chunk file upload using JavaScript and PHP.
Step 1: HTML Markup
Let’s start by creating the HTML markup for the file upload form. Open a new HTML file and add the following code:
<!DOCTYPE html> <html> <head> <title>Chunk File Upload</title> </head> <body> <form id="upload-form" enctype="multipart/form-data"> <input type="file" id="file-input" name="file" /> <button type="button" id="upload-button">Upload</button> <div id="progress-bar"></div> </form> <script src="upload.js"></script> </body> </html>
In the above code, we have a simple file upload form with an input field, a button, and a progress bar. The form has an ID of “upload-form” and the file input field has an ID of “file-input”. We also include a JavaScript file named “upload.js” where we will write our client-side code.
Step 2: Client-side JavaScript Code
Create a new JavaScript file named “upload.js” and add the following code:
document.getElementById('upload-button').addEventListener('click', function() { var fileInput = document.getElementById('file-input'); var file = fileInput.files[0]; if (file) { uploadFile(file); } }); function uploadFile(file) { var fileSize = file.size; var chunkSize = 1024 * 1024; // 1MB var offset = 0; var reader = new FileReader(); reader.onload = function() { var chunk = reader.result; var formData = new FormData(); formData.append('file', chunk); formData.append('offset', offset); var xhr = new XMLHttpRequest(); xhr.open('POST', 'upload.php', true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.upload.onprogress = function(event) { var percent = (event.loaded / event.total) * 100; document.getElementById('progress-bar').style.width = percent + '%'; }; xhr.onload = function() { offset += chunkSize; if (offset < fileSize) { uploadFileSlice(); } else { // File upload complete document.getElementById('progress-bar').style.width = '100%'; alert('File uploaded successfully!'); } }; xhr.send(formData); }; function uploadFileSlice() { var slice = file.slice(offset, offset + chunkSize); reader.readAsDataURL(slice); } uploadFileSlice(); }
In the above code, we first listen for the click event on the “upload-button”. When the button is clicked, we get the selected file from the file input field.
The uploadFile function is responsible for handling the file upload process. It first calculates the file size and sets the chunk size to 1MB (you can adjust this value based on your requirements). The offset variable keeps track of the current position in the file.
Next, we create a FileReader object and set its onload event handler. Inside the onload callback function, we read the chunk of the file using reader.result and create a FormData object to store the chunk and offset.
We then create an XMLHttpRequest object and configure it for a POST request to the “upload.php” file. We set the X-Requested-With header to indicate an XMLHttpRequest.
The xhr.upload.onprogress event handler updates the progress bar based on the percentage of the uploaded data.
The xhr.onload event handler is called when the chunk is successfully uploaded. It updates the offset and checks if there are more chunks to upload. If there are more chunks, it calls the uploadFileSlice function recursively. Otherwise, it displays a completion message.
The uploadFileSlice function slices the file into chunks based on the offset and chunk size and reads each chunk using the FileReader.
Step 3: Server-side PHP Code
Now, let’s create the server-side PHP code to handle the file upload. Create a new file named “upload.php” and add the following code:
<?php $targetDir = 'uploads/'; if (!empty($_FILES['file']['tmp_name'])) { $file = $_FILES['file']['tmp_name']; $offset = isset($_POST['offset']) ? (int)$_POST['offset'] : 0; $fileName = basename($_FILES['file']['name']); $targetFile = $targetDir . $fileName; if ($offset === 0) { // Create a new file file_put_contents($targetFile, ''); } file_put_contents($targetFile, file_get_contents($file), FILE_APPEND | LOCK_EX); echo 'Chunk uploaded successfully!'; } ?>
In the above PHP code, we first specify the target directory where the uploaded chunks will be stored. Make sure to create the “uploads” directory and grant appropriate permissions to write files.
We check if the uploaded file exists and retrieve its temporary name, offset, and original file name. We then create the target file path by combining the target directory and file name.
If the offset is 0, it means it’s the first chunk of the file, so we create a new file. Otherwise, we append the chunk data to the existing file using file_put_contents.
Finally, we echo a success message to indicate that the chunk has been uploaded successfully.
Step 4: Testing the Chunk File Upload
Now, you can test the chunk file upload by running the HTML file in your web browser. Select a large file using the file input field and click the “Upload” button. The file will be divided into chunks and uploaded sequentially. The progress bar will indicate the progress of the upload.
Once the upload is complete, you will see an alert message indicating the successful upload.
In this article, we have explored how to implement chunk file upload using JavaScript and PHP. This technique allows for the efficient uploading of large files by breaking them into smaller chunks. By dividing the file into chunks and uploading them sequentially, we can overcome limitations imposed by web servers or browsers. Implementing chunk file upload enhances the user experience and ensures the successful transfer of large files in web applications.
Comments