DEV Community

Cover image for File Upload with Progress Bar HTML CSS JS & PHP
Hassan Ali
Hassan Ali

Posted on • Originally published at hassanrao.com on

File Upload with Progress Bar HTML CSS JS & PHP

Hello there, today in this blog I’ll show you how to make a File Uploader with Progress in HTML CSS JavaScript & PHP. There is a box with a dashed border, as seen in the preview image. Click anywhere in the box to pick a file. Your selected file will be shown below that box, along with its status (in progress or complete), upload percentage, progress bar, file name, file size, and so on. The history of your previously uploaded files will be listed as finished, however the history will be lost on page refresh.

I hope you like my File Uploader and would want to obtain the source code or files for this project. Don’t worry, I have included a download link for the source code and files at the bottom of the page. Nevertheless, before you copy-paste the codes or download the files, let’s go through the key codes and principles that went into making this file uploader.

I used the change event in the JavaScript code to acquire the user-selected filename and then used the uploadFile(filename) method with the filename as an input. Using Ajax, I passed the selected file to PHP within the uploadFile() method. As you can see from the code, I utilised the upload property and the progress event to retrieve the file loaded value and total size.

In the PHP code, I got the file and prefixed it with the current time to make the filename dynamic, then transferred it to the files folder using the PHP inbuilt function move_uploaded_file().

JS File Uploader With Progress Bar(Source Code):

You must first create four files: two PHP files, one CSS file, and one JavaScript file (All In Root Folder). When you’ve created these files, just copy and paste the following codes into your file. Remember to create a “uploaded files” folder in the root folder to save all uploaded files over time.

If you don’t understand, you can get the source code files for this File Upload JavaScript with Progress Bar by clicking the download button.

Step One: create an PHP file with the name of index.php and paste the given codes into your php file. Remember, you’ve to create a file with .php extension. You may also use the .html or.htm extension for this file. Even though, I usually consider using the php file extension for all html file when working with php because sometimes php code does not work with .html files.

<!DOCTYPE html>
<!-- By HassanRao - hassanrao.com -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Uploader | Hassanrao.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="wrapper">
    <header> JS File Uploader</header>
    <form action="#">
      <input class="file-input" type="file" name="file" hidden>
      <i class="fas fa-cloud-upload-alt"></i>
      <p>Click to select one file at a time.</p>
    </form>
    <section class="progress-area"></section>
    <section class="uploaded-area"></section>
  </div>

  <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

*Step Two: * Create a CSS file called style.css and paste the following codes into it. Remember to save the file with the .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #04d476;
}

::selection{
  color: #fff;
  background: #04d476;
}
.wrapper{
  width: 430px;
  background: #fff;
  border-radius: 5px;
  padding: 30px;
  box-shadow: 7px 7px 12px rgba(0,0,0,0.05);
}
.wrapper header{
  color: #04d476;
  font-size: 27px;
  font-weight: 600;
  text-align: center;
}
.wrapper small{
  text-align:center;
  color:#038249;
}
.wrapper form{
  height: 167px;
  display: flex;
  cursor: pointer;
  margin: 30px 0;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-radius: 5px;
  border: 2px dashed #04d476;
}
form :where(i, p){
  color: #04d476;
}
form i{
  font-size: 50px;
}
form p{
  margin-top: 15px;
  font-size: 16px;
}

section .row{
  margin-bottom: 10px;
  background: #E9F0FF;
  list-style: none;
  padding: 15px 20px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
section .row i{
  color: #04d476;
  font-size: 30px;
}
section .details span{
  font-size: 14px;
}
.progress-area .row .content{
  width: 100%;
  margin-left: 15px;
}
.progress-area .details{
  display: flex;
  align-items: center;
  margin-bottom: 7px;
  justify-content: space-between;
}
.progress-area .content .progress-bar{
  height: 6px;
  width: 100%;
  margin-bottom: 4px;
  background: #fff;
  border-radius: 30px;
}
.content .progress-bar .progress{
  height: 100%;
  width: 0%;
  background: #04d476;
  border-radius: inherit;
}
.uploaded-area{
  max-height: 232px;
  overflow-y: scroll;
}
.uploaded-area.onprogress{
  max-height: 150px;
}
.uploaded-area::-webkit-scrollbar{
  width: 0px;
}
.uploaded-area .row .content{
  display: flex;
  align-items: center;
}
.uploaded-area .row .details{
  display: flex;
  margin-left: 15px;
  flex-direction: column;
}
.uploaded-area .row .details .size{
  color: #404040;
  font-size: 11px;
}
.uploaded-area i.fa-check{
  font-size: 16px;
}

Enter fullscreen mode Exit fullscreen mode

Step Three: create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with .js extension.

const form = document.querySelector("form"),
fileInput = document.querySelector(".file-input"),
progressArea = document.querySelector(".progress-area"),
uploadedArea = document.querySelector(".uploaded-area");

// form click event
form.addEventListener("click", () =>{
  fileInput.click();
});

fileInput.onchange = ({target})=>{
  let file = target.files[0]; //getting file [0] this means if user has selected multiple files then get first one only
  if(file){
    let fileName = file.name; //getting file name
    if(fileName.length >= 12){ //if file name length is greater than 12 then split it and add ...
      let splitName = fileName.split('.');
      fileName = splitName[0].substring(0, 13) + "... ." + splitName[1];
    }
    uploadFile(fileName); //calling uploadFile with passing file name as an argument
  }
}

// file upload function
function uploadFile(name){
  let xhr = new XMLHttpRequest(); //creating new xhr object (AJAX)
  xhr.open("POST", "upload.php"); //sending post request to the specified URL
  xhr.upload.addEventListener("progress", ({loaded, total}) =>{ //file uploading progress event
    let fileLoaded = Math.floor((loaded / total) * 100); //getting percentage of loaded file size
    let fileTotal = Math.floor(total / 1000); //gettting total file size in KB from bytes
    let fileSize;
    // if file size is less than 1024 then add only KB else convert this KB into MB
    (fileTotal < 1024) ? fileSize = fileTotal + " KB" : fileSize = (loaded / (1024*1024)).toFixed(2) + " MB";
    let progressHTML = `<li class="row">
                          <i class="fas fa-file-alt"></i>
                          <div class="content">
                            <div class="details">
                              <span class="name">${name} • Uploading</span>
                              <span class="percent">${fileLoaded}%</span>
                            </div>
                            <div class="progress-bar">
                              <div class="progress" style="width: ${fileLoaded}%"></div>
                            </div>
                          </div>
                        </li>`;
    // uploadedArea.innerHTML = ""; //uncomment this line if you don't want to show upload history
    uploadedArea.classList.add("onprogress");
    progressArea.innerHTML = progressHTML;
    if(loaded == total){
      progressArea.innerHTML = "";
      let uploadedHTML = `<li class="row">
                            <div class="content upload">
                              <i class="fas fa-file-alt"></i>
                              <div class="details">
                                <span class="name">${name} • Uploaded</span>
                                <span class="size">${fileSize}</span>
                              </div>
                            </div>
                            <i class="fas fa-check"></i>
                          </li>`;
      uploadedArea.classList.remove("onprogress");
      // uploadedArea.innerHTML = uploadedHTML; //uncomment this line if you don't want to show upload history
      uploadedArea.insertAdjacentHTML("afterbegin", uploadedHTML); //remove this line if you don't want to show upload history
    }
  });
  let data = new FormData(form); //FormData is an object to easily send form data
  xhr.send(data); //sending form data
}
Enter fullscreen mode Exit fullscreen mode

Final Step: Create a PHP file called upload.php and insert the following scripts into it. Remember to save the file with the .php extension.

<?php
  $file_name = $_FILES['file']['name']; //getting file name
  $tmp_name = $_FILES['file']['tmp_name']; //getting temp_name of file
  move_uploaded_file($tmp_name, "uploaded files/".$file_name); //moving file to the specified folder
?>
Enter fullscreen mode Exit fullscreen mode

If this Code or zip file code doesn’t work then please ensure that you have a folder in root directory with name as “uploaded files” because file zipper removes empty folders.

View This Post On Hassanrao.com for free source Files download Link.

Top comments (0)