Home  >  Article  >  Web Front-end  >  How to add file upload function to HTML web page?

How to add file upload function to HTML web page?

王林
王林forward
2023-09-04 12:29:051717browse

How to add file upload function to HTML web page?

Introduction

In this article, we'll walk you through the process of adding file upload capabilities to your web pages. We'll show you how to create an HTML form with file input fields, and how to create a script that handles the file upload process.

method

We can use the following two methods to add file upload functionality to HTML web pages -

  • Using a basic HTML form with a file input field

  • Using jQuery and ajax

Now let us discuss them in detail.

Method 1: Use a basic HTML form with a file input field

This method involves creating a simple HTML form that contains a file input field that allows the user 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 with an example.

Example

Let us understand this better with 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 that contains a file input field that allows the user to select a file to upload, and a submit button for sending the form. The action attribute is set to "upload.php", which is the server-side script that handles file uploads. The enctype attribute is set to "multipart/form-data", which is required for file uploads.

Step 3 - Create a server-side PHP script (action.php) to handle file uploads.

<?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 if the file input field contains a file using the isset function and the $_FILES superglobal variable. The script then checks the file size and file extension using the in_array function and a predefined list of allowed file extensions. If the file is valid, use the move_uploaded_file function to move it to the "upload" directory on the server. If the file is invalid, an error message is displayed.

Method 2: Using jQuery and ajax

This method is a more advanced way of handling file uploads, allowing you to handle the file upload process without refreshing the page.

Step 1 - Create a file named index.html

Step 2 - Include jQuery and the jQuery form plugin in this file -

Example

Let’s understand this better with 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 jQuery and the jQuery Form Plugin library in the HTML document. These libraries will allow you to handle the file upload process through JavaScript using the ajaxForm method.

Step 3 Create an HTML form with file input fields -

<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 that contains 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 set the enctype attribute to "multipart/form-data" since that is where the file upload is. Required.

Step 4 - Use jQuery to handle file uploads -

$(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 various stages of the file upload process.

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

Step 5 - Complete HTML with the jQuery code for the index.html file goes 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 a PHP server-side script (upload.php) to handle file uploads -

<?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);
      }
   }
?>

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

in conclusion

In this article, we discussed two ways to add file upload functionality in HTML web pages. The first method is to use a basic HTML form with a file input field and then send that form to a server-side script that handles the actual saving of the file. The second method is to use jQuery and ajax, this method allows you to handle the file upload process without refreshing the page.

Both methods require proper validation, the correct way to store the file, the correct permissions on the server side, and the correct way to sanitize the filename and extension for security reasons.

The above is the detailed content of How to add file upload function to HTML web page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete