{"id":134165,"date":"2023-06-17T06:21:34","date_gmt":"2023-06-17T06:21:34","guid":{"rendered":"https:\/\/phppot.com\/?p=20937"},"modified":"2023-06-17T06:21:34","modified_gmt":"2023-06-17T06:21:34","slug":"ajax-file-upload-with-progress-bar-using-javascript","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/06\/17\/ajax-file-upload-with-progress-bar-using-javascript\/","title":{"rendered":"AJAX File Upload with Progress Bar using JavaScript"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.0697674418605\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on June 30th, 2023.<\/div>\n<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>\n<p>This article has an example code for JavaScript AJAX file upload with a progress bar.<\/p>\n<p>An AJAX-based file upload is a repeatedly needed requirement for a web application.<\/p>\n<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>\n<ol>\n<li>Photo or banner update on the profile page.<\/li>\n<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>\n<\/ol>\n<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\/2023\/06\/ajax-file-upload-with-progress-bar-javascript-300x200.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/06\/ajax-file-upload-with-progress-bar-javascript-768x512.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/06\/ajax-file-upload-with-progress-bar-javascript.jpg 1200w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>HTML upload form<\/h2>\n<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>\n<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>\n<p>But in this example, the HTML doesn\u2019t have any form container. Instead, the form data is created by JavaScript before processing the AJAX.<\/p>\n<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>\n<pre class=\"prettyprint\"><code class=\"language-html\">&lt;div class=\"phppot-container tile-container text-center\"&gt; &lt;h2&gt;AJAX File Upload with Progress Bar using JavaScript&lt;\/h2&gt; &lt;input type=\"file\" id=\"fileUpload\" \/&gt; &lt;br&gt; &lt;br&gt; &lt;button onclick=\"uploadFile()\"&gt;Upload&lt;\/button&gt; &lt;div class=\"progress\"&gt; &lt;div class=\"progress-bar\" id=\"progressBar\"&gt;&lt;\/div&gt; &lt;\/div&gt; &lt;br&gt; &lt;div id=\"uploadStatus\"&gt;&lt;\/div&gt;\n&lt;\/div&gt;\n<\/code><\/pre>\n<h2>AJAX file upload request with progress bar<\/h2>\n<p>This section is the core of this example code. This example\u2019s 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>\n<p>The script below follows the steps to achieve the AJAX file upload.<\/p>\n<ol>\n<li>It reads the file binary chosen in the file input field.<\/li>\n<li>It instantiates JavaScript FormData and appends the file binary into it.<\/li>\n<li>It creates an XMLHttpRequest handle.<\/li>\n<li>This handle uses the \u2018upload\u2019 property to get <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/XMLHttpRequest\/upload\" target=\"_blank\" rel=\"noopener\">XMLHttpRequestUpload object<\/a>.<\/li>\n<li>This XMLHttpRequestUpload object tracks the upload progress in percentage.<\/li>\n<li>It creates event listeners to update the progressing percentage and the upload status.<\/li>\n<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>\n<\/ol>\n<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); }\n}\n<\/code><\/pre>\n<h2>PHP endpoint to move the uploaded file into a directory<\/h2>\n<p>This PHP&nbsp; 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>\n<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>\n<p>It is for stopping file overwriting in case of uploading different files in the same name.<\/p>\n<p><strong>Note:<\/strong> <span>Create a folder named \u201cuploads\u201d in the project root. Give sufficient write permissions.<\/span><\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php if ($_SERVER['REQUEST_METHOD'] === 'POST' &amp;&amp; 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.'; }\n}\n<\/code><\/pre>\n<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>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/ajax-file-upload-with-progress-bar-using-javascript\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on June 30th, 2023. 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. This article has an example code for JavaScript AJAX file upload with a progress bar. An AJAX-based file upload is [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":134166,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-134165","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134165","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=134165"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134165\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/134166"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=134165"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=134165"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=134165"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}