How to add a file uploads function to a webpage in HTML?


Introduction

In this article, we will walk you through the process of adding a file upload function to your webpage. We will show you how to create an HTML form with a file input field, as well as how to create a script that handles the file upload process.

Approaches

Two approaches that we can use to add a file upload function to our webpage in HTML are as follows −

  • Using a basic HTML form with a file input field

  • Using jQuery and ajax

Let us discuss them in detail now.

Approach 1: Using a basic HTML form with a file input field

This method involves creating a simple HTML form with a file input field that allows users to select a file to upload. The form is then sent to a server-side script that handles the actual saving of the file.

Step 1 − Create a file called index.html.

Step 2 − Create an HTML form with a file input field.

Example

Let us understand this better through an example.

<!DOCTYPE html>
<html>
<head>
   <title>File Upload</title>
</head>
<body>
   <h1>Welcome to Tutorials Point</h1>
   <form action="upload.php" method="post" enctype="multipart/form-data">
      <input type="file" name="uploadedFile">
      <input type="submit" value="Upload">
   </form>
</body>
</html>

This will create an HTML form with a file input field that allows the user to select a file to upload, and a submit button to send the form. The action attribute is set to "upload.php", which is the server-side script that will handle the file upload. The enctype attribute is set to "multipart/form-data", which is necessary for file uploads.

Step 3 − Create the server-side PHP script (action.php) to handle the file upload.

<?php
   if(isset($_FILES['uploadedFile'])){
      $errors= array();
      $file_name = $_FILES['uploadedFile']['name'];
      $file_size = $_FILES['uploadedFile']['size'];
      $file_tmp = $_FILES['uploadedFile']['tmp_name'];
      $file_type = $_FILES['uploadedFile']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));
      $extensions= array("jpeg","jpg","png");

      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"upload/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>

This script first checks whether the file input field contains a file using the isset function and the $_FILES superglobal. The script then checks the file size and file extension using the in_array function and a pre-defined list of allowed file extensions. If the file is valid, it is moved to the "upload" directory on the server using the move_uploaded_file function. If the file is not valid, an error message is displayed.

Approach 2: Using jQuery and ajax

This method is a more advanced method of handling file uploads, and allows you to handle the file upload process without having to refresh the page.

Step 1 − Create a file called index.html

Step 2 − Include jQuery and jQuery Form Plugin in this file −

Example

Let us understand this better through an example.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://malsup.github.io/jquery.form.js"></script>

This step involves including the jQuery and jQuery Form Plugin libraries in your HTML document. These libraries will allow you to use the ajaxForm method to handle the file upload process via JavaScript.

Step 3 − Create an HTML form with a file input field −

<form id="fileUploadForm" action="upload.php" method="post" enctype="multipart/form-data">
   <input type="file" name="uploadedFile">
   <input type="submit" value="Upload">
</form>

This step is similar to step 1 of method 1. You create an HTML form with a file input field, and a submit button, and set the action attribute to point to the server-side script that will handle the file upload, and the enctype attribute to "multipart/form-data" as it is necessary for file uploads.

Step 4 − Use jQuery to handle the file upload −

$(document).ready(function(){
   $('#fileUploadForm').ajaxForm({
      beforeSubmit: function(){
         
         // do validation here
         var fileInput = document.getElementById('fileInput');
         var file = fileInput.files[0];
         var maxFileSize = 2097152; // 2 MB
         var validFileExtensions = ["jpg", "jpeg", "png"];
         var extension = file.name.split('.').pop().toLowerCase();
         if(file.size > maxFileSize) {
            alert("File size must be exactly 2 MB.");
            return false;
         }
         if(validFileExtensions.indexOf(extension) === -1) {
            alert("Invalid file type. Only JPEG and PNG files are allowed.");
            return false;
         }
      },
      success: function(response){
         
         // handle response
         var jsonResponse = JSON.parse(response);
         if(jsonResponse.status === "success"){
            alert("File upload successful!");
         }else{
            alert("File upload failed. Please try again.");
         }
      },
      error: function(response){
         
         // handle errors
         alert("There was an error while uploading the file. Please try again later.");
      }
   });
});

This step involves using jQuery to handle the file upload process. The ajaxForm method is used to submit the form via JavaScript, and the beforeSubmit, success, and error functions are used to handle the various stages of the file upload process.

The beforeSubmit function is used to validate the file before uploading, and the success function is used to handle the server's response after the file is uploaded. The error function is used to handle any errors that occur during the file upload process.

Step 5 − Complete HTML with jQuery code for the index.html file is here −

Example

<!DOCTYPE html>
<html>
<head>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://malsup.github.io/jquery.form.js"></script>
</head>
<body>
   <h1>Greetings from Tutorials Point!</h1>
   <form id="fileUploadForm" action="upload.php" method="post" enctype="multipart/form-data">
      <input type="file" name="uploadedFile">
      <input type="submit" value="Upload">
   </form>
   <script>
      $(document).ready(function(){
         $('#fileUploadForm').ajaxForm({
            beforeSubmit: function(){
               
               // do validation here
               var fileInput = document.getElementById('fileInput');
               var file = fileInput.files[0];
               var maxFileSize = 2097152; // 2 MB
               var validFileExtensions = ["jpg", "jpeg", "png"];
               var extension = file.name.split('.').pop().toLowerCase();
               if(file.size > maxFileSize) {
                  alert("File size must be exactly 2 MB.");
                  return false;
               }
               if(validFileExtensions.indexOf(extension) === -1) {
                  alert("Invalid file type. Only JPEG and PNG files are allowed.");
                  return false;
               }
            },
            success: function(response){
            
               // handle response
               var jsonResponse = JSON.parse(response);
               if(jsonResponse.status === "success"){
                  alert("File upload successful!");
               }else{
                  alert("File upload failed. Please try again.");
               }
            },
            error: function(response){
               
               // handle errors
               alert("There was an error while uploading the file. Please try again later.");
            }
         });
      });
   </script>
</body>
</html>

Step 6 − Create the PHP server-side script (upload.php) to handle the file upload −

<?php
   if(isset($_FILES['uploadedFile'])){
      $errors= array();
      $file_name = $_FILES['uploadedFile']['name'];
      $file_size = $_FILES['uploadedFile']['size'];
      $file_tmp = $_FILES['uploadedFile']['tmp_name'];
      $file_type = $_FILES['uploadedFile']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));

      $extensions= array("jpeg","jpg","png");

      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"upload/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>

This script first checks whether the file input field contains a file using the isset function and the $_FILES superglobal. The script then checks the file size and file extension using the in_array function and a pre-defined list of allowed file extensions. If the file is valid, it is moved to the "upload" directory on the server using the move_uploaded_file.

Conclusion

In this article, we have discussed two approaches to adding a file upload function to a webpage in HTML. The first method is using a basic HTML form with a file input field, the form is then sent to a server-side script that handles the actual saving of the file. The second method is using jQuery and ajax, this method allows you to handle the file upload process without having to refresh the page.

Both methods require proper validation, a proper way of storing the file, with the right permissions on the server side, and also a proper way of sanitizing file names and extensions for security reasons.

Updated on: 31-Jan-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements