08-20-2023, 12:34 AM
[Tut] AJAX File Upload with Progress Bar using JavaScript
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/08/ajax-file-upload-with-progress-bar-using-javascript.jpg" width="550" height="367" title="" alt="" /></div><div><div class="modified-on" readability="7.0697674418605"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on June 30th, 2023.</div>
<p>If you want to upload a file using AJAX and also need to show a progress bar during the upload, you have landed on the right page.</p>
<p>This article has an example code for JavaScript AJAX file upload with a progress bar.</p>
<p>An AJAX-based file upload is a repeatedly needed requirement for a web application.</p>
<p>It is for providing an inline editing feature with the uploaded file content. For example, the following tasks can be achieved using the AJAX file upload method.</p>
<ol>
<li>Photo or banner update on the profile page.</li>
<li><a href="https://phppot.com/php/import-csv-file-into-mysql-using-php/">Import CSV</a> or Excel files to load content to the data tables.</li>
</ol>
<p><a class="demo" href="https://phppot.com/demo/php-upload-progress-bar/">View demo</a><br /><img decoding="async" loading="lazy" class="alignnone size-large wp-image-21088" src="https://phppot.com/wp-content/uploads/2023/06/ajax-file-upload-with-progress-bar-javascript-550x367.jpg" alt="ajax file upload with progress bar javascript" width="550" height="367" srcset="https://phppot.com/wp-content/uploads/2023/06/ajax-file-upload-with-progress-bar-javascript-550x367.jpg 550w, https://phppot.com/wp-content/uploads/20...00x200.jpg 300w, https://phppot.com/wp-content/uploads/20...68x512.jpg 768w, https://phppot.com/wp-content/uploads/20...script.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>HTML upload form</h2>
<p>This HTML shows the input to choose a file. This form has a button that maps its click event with an AJAX handler.</p>
<p>In a previous tutorial, we have seen a <a href="https://phppot.com/jquery/jquery-ajax-image-upload/">jQuery example for uploading form data with a chosen file binary</a>.</p>
<p>But in this example, the HTML doesn’t have any form container. Instead, the form data is created by JavaScript before processing the AJAX.</p>
<p>This HTML has a container to show the progress bar. Once the progress is 100% complete, a success message is added to the UI without page refresh.</p>
<pre class="prettyprint"><code class="language-html"><div class="phppot-container tile-container text-center"> <h2>AJAX File Upload with Progress Bar using JavaScript</h2> <input type="file" id="fileUpload" /> <br> <br> <button onclick="uploadFile()">Upload</button> <div class="progress"> <div class="progress-bar" id="progressBar"></div> </div> <br> <div id="uploadStatus"></div>
</div>
</code></pre>
<h2>AJAX file upload request with progress bar</h2>
<p>This section is the core of this example code. This example’s HTML and PHP files are prevalent, as seen in other <a href="https://phppot.com/php/working-on-file-upload-using-php/">file upload examples</a>.</p>
<p>The script below follows the steps to achieve the AJAX file upload.</p>
<ol>
<li>It reads the file binary chosen in the file input field.</li>
<li>It instantiates JavaScript FormData and appends the file binary into it.</li>
<li>It creates an XMLHttpRequest handle.</li>
<li>This handle uses the ‘upload’ property to get <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload" target="_blank" rel="noopener">XMLHttpRequestUpload object</a>.</li>
<li>This XMLHttpRequestUpload object tracks the upload progress in percentage.</li>
<li>It creates event listeners to update the progressing percentage and the upload status.</li>
<li>Then finally, it posts the file to the PHP endpoint like usual <a href="https://phppot.com/php/ajax-programming-with-php/">AJAX programming</a>.</li>
</ol>
<pre class="prettyprint"><code class="language-javascript">function uploadFile() { var fileInput = document.getElementById('fileUpload'); var file = fileInput.files[0]; if (file) { var formData = new FormData(); formData.append('file', file); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function (event) { if (event.lengthComputable) { var percent = Math.round((event.loaded / event.total) * 100); var progressBar = document.getElementById('progressBar'); progressBar.style.width = percent + '%'; progressBar.innerHTML = percent + '%'; } }); xhr.addEventListener('load', function (event) { var uploadStatus = document.getElementById('uploadStatus'); uploadStatus.innerHTML = event.target.responseText; }); xhr.open('POST', 'upload.php', true); xhr.send(formData); }
}
</code></pre>
<h2>PHP endpoint to move the uploaded file into a directory</h2>
<p>This PHP has a standard code to store the uploaded file in a folder using the PHP move_uploaded_file(). The link has the code if you want to store the <a href="https://phppot.com/php/php-file-upload/">uploaded file and save the path to the database</a>.</p>
<p>This endpoint creates a unique name for the filename before upload. It is a good programming practice, but the code will work without it, also.</p>
<p>It is for stopping file overwriting in case of uploading different files in the same name.</p>
<p><strong>Note:</strong> <span>Create a folder named “uploads” in the project root. Give sufficient write permissions.</span></p>
<pre class="prettyprint"><code class="language-php"><?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $file = $_FILES['file']; // file will be uploaded to the following folder // you should give sufficient file permissions $uploadDir = 'uploads/'; // unique file name generated $fileName = uniqid() . '_' . $file['name']; // moving the uploaded file from temp location to our target location if (move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) { echo 'File uploaded successfully.'; } else { echo 'Failed to upload file.'; }
}
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/php-upload-progress-bar/">View demo</a> <a class="download" href="https://phppot.com/downloads/php/ajax-file-upload-progress-bar.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/ajax-file-upload-with-progress-bar-using-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2023/06/...avascript/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/08/ajax-file-upload-with-progress-bar-using-javascript.jpg" width="550" height="367" title="" alt="" /></div><div><div class="modified-on" readability="7.0697674418605"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on June 30th, 2023.</div>
<p>If you want to upload a file using AJAX and also need to show a progress bar during the upload, you have landed on the right page.</p>
<p>This article has an example code for JavaScript AJAX file upload with a progress bar.</p>
<p>An AJAX-based file upload is a repeatedly needed requirement for a web application.</p>
<p>It is for providing an inline editing feature with the uploaded file content. For example, the following tasks can be achieved using the AJAX file upload method.</p>
<ol>
<li>Photo or banner update on the profile page.</li>
<li><a href="https://phppot.com/php/import-csv-file-into-mysql-using-php/">Import CSV</a> or Excel files to load content to the data tables.</li>
</ol>
<p><a class="demo" href="https://phppot.com/demo/php-upload-progress-bar/">View demo</a><br /><img decoding="async" loading="lazy" class="alignnone size-large wp-image-21088" src="https://phppot.com/wp-content/uploads/2023/06/ajax-file-upload-with-progress-bar-javascript-550x367.jpg" alt="ajax file upload with progress bar javascript" width="550" height="367" srcset="https://phppot.com/wp-content/uploads/2023/06/ajax-file-upload-with-progress-bar-javascript-550x367.jpg 550w, https://phppot.com/wp-content/uploads/20...00x200.jpg 300w, https://phppot.com/wp-content/uploads/20...68x512.jpg 768w, https://phppot.com/wp-content/uploads/20...script.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>HTML upload form</h2>
<p>This HTML shows the input to choose a file. This form has a button that maps its click event with an AJAX handler.</p>
<p>In a previous tutorial, we have seen a <a href="https://phppot.com/jquery/jquery-ajax-image-upload/">jQuery example for uploading form data with a chosen file binary</a>.</p>
<p>But in this example, the HTML doesn’t have any form container. Instead, the form data is created by JavaScript before processing the AJAX.</p>
<p>This HTML has a container to show the progress bar. Once the progress is 100% complete, a success message is added to the UI without page refresh.</p>
<pre class="prettyprint"><code class="language-html"><div class="phppot-container tile-container text-center"> <h2>AJAX File Upload with Progress Bar using JavaScript</h2> <input type="file" id="fileUpload" /> <br> <br> <button onclick="uploadFile()">Upload</button> <div class="progress"> <div class="progress-bar" id="progressBar"></div> </div> <br> <div id="uploadStatus"></div>
</div>
</code></pre>
<h2>AJAX file upload request with progress bar</h2>
<p>This section is the core of this example code. This example’s HTML and PHP files are prevalent, as seen in other <a href="https://phppot.com/php/working-on-file-upload-using-php/">file upload examples</a>.</p>
<p>The script below follows the steps to achieve the AJAX file upload.</p>
<ol>
<li>It reads the file binary chosen in the file input field.</li>
<li>It instantiates JavaScript FormData and appends the file binary into it.</li>
<li>It creates an XMLHttpRequest handle.</li>
<li>This handle uses the ‘upload’ property to get <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload" target="_blank" rel="noopener">XMLHttpRequestUpload object</a>.</li>
<li>This XMLHttpRequestUpload object tracks the upload progress in percentage.</li>
<li>It creates event listeners to update the progressing percentage and the upload status.</li>
<li>Then finally, it posts the file to the PHP endpoint like usual <a href="https://phppot.com/php/ajax-programming-with-php/">AJAX programming</a>.</li>
</ol>
<pre class="prettyprint"><code class="language-javascript">function uploadFile() { var fileInput = document.getElementById('fileUpload'); var file = fileInput.files[0]; if (file) { var formData = new FormData(); formData.append('file', file); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function (event) { if (event.lengthComputable) { var percent = Math.round((event.loaded / event.total) * 100); var progressBar = document.getElementById('progressBar'); progressBar.style.width = percent + '%'; progressBar.innerHTML = percent + '%'; } }); xhr.addEventListener('load', function (event) { var uploadStatus = document.getElementById('uploadStatus'); uploadStatus.innerHTML = event.target.responseText; }); xhr.open('POST', 'upload.php', true); xhr.send(formData); }
}
</code></pre>
<h2>PHP endpoint to move the uploaded file into a directory</h2>
<p>This PHP has a standard code to store the uploaded file in a folder using the PHP move_uploaded_file(). The link has the code if you want to store the <a href="https://phppot.com/php/php-file-upload/">uploaded file and save the path to the database</a>.</p>
<p>This endpoint creates a unique name for the filename before upload. It is a good programming practice, but the code will work without it, also.</p>
<p>It is for stopping file overwriting in case of uploading different files in the same name.</p>
<p><strong>Note:</strong> <span>Create a folder named “uploads” in the project root. Give sufficient write permissions.</span></p>
<pre class="prettyprint"><code class="language-php"><?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $file = $_FILES['file']; // file will be uploaded to the following folder // you should give sufficient file permissions $uploadDir = 'uploads/'; // unique file name generated $fileName = uniqid() . '_' . $file['name']; // moving the uploaded file from temp location to our target location if (move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) { echo 'File uploaded successfully.'; } else { echo 'Failed to upload file.'; }
}
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/php-upload-progress-bar/">View demo</a> <a class="download" href="https://phppot.com/downloads/php/ajax-file-upload-progress-bar.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/ajax-file-upload-with-progress-bar-using-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2023/06/...avascript/